From f30ac61048863f85f231121fca9933798a3f06c8 Mon Sep 17 00:00:00 2001 From: Jari Kanerva Date: Sun, 13 Dec 2009 05:36:27 +0000 Subject: [PATCH] Moved into directories. --- COPYING | 340 +++++++++++++++ README | 15 + config.php | 43 ++ constants.php | 36 ++ diff/Diff.php | 454 ++++++++++++++++++++ diff/Renderer.php | 236 +++++++++++ diff/inline.php | 177 ++++++++ diff/native.php | 438 +++++++++++++++++++ functions.php | 145 +++++++ modx_gen.php | 212 ++++++++++ modx_writer.php | 225 ++++++++++ parse_diff.php | 1035 +++++++++++++++++++++++++++++++++++++++++++++ 12 files changed, 3356 insertions(+) create mode 100644 COPYING create mode 100644 README create mode 100644 config.php create mode 100644 constants.php create mode 100644 diff/Diff.php create mode 100644 diff/Renderer.php create mode 100644 diff/inline.php create mode 100644 diff/native.php create mode 100644 functions.php create mode 100644 modx_gen.php create mode 100644 modx_writer.php create mode 100644 parse_diff.php diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..b860267 --- /dev/null +++ b/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/README b/README new file mode 100644 index 0000000..f383eca --- /dev/null +++ b/README @@ -0,0 +1,15 @@ +"Phiff" is a MODX generator that attempts to run a diff and then generate a MODX file with inline edits. + +Do note that this is early beta. Read the issues file. + +Authors: Jari Kanerva (tumba25) + +USAGE: +php modx_diff.php -o path/to/unchanged/dir (or file) -n path/to/changed/dir (or file) + +The parameters to modx_diff.php needs to be after "php modx_diff.php". +-o, --old = The original files, with path from / or the current dir. +-n, --new = The modified files, with path from / or the current dir. + Both old and new need to be either files or dirs. +-f, --outfile = path and name of file to generate. Defautls to ./install_mod.xml +-v, --verbose = Tell what happens. diff --git a/config.php b/config.php new file mode 100644 index 0000000..acbeee6 --- /dev/null +++ b/config.php @@ -0,0 +1,43 @@ +, and is used/adapted with his permission. + * + * $Horde: framework/Text_Diff/Diff.php,v 1.11.2.12 2009/01/06 15:23:41 jan Exp $ + * + * Copyright 2004 Geoffrey T. Dairiki + * Copyright 2004-2009 The Horde Project (http://www.horde.org/) + * + * See the enclosed file COPYING for license information (LGPL). If you did + * not receive this file, see http://opensource.org/licenses/lgpl-license.php. + * + * @package Text_Diff + * @author Geoffrey T. Dairiki + */ +class Text_Diff { + + /** + * Array of changes. + * + * @var array + */ + var $_edits; + + /** + * Computes diffs between sequences of strings. + * + * @param string $engine Name of the diffing engine to use. 'auto' + * will automatically select the best. + * @param array $params Parameters to pass to the diffing engine. + * Normally an array of two arrays, each + * containing the lines from a file. + */ + function Text_Diff($engine, $params) + { + // Backward compatibility workaround. + if (!is_string($engine)) { + $params = array($engine, $params); + $engine = 'auto'; + } + + if ($engine == 'auto') { + $engine = extension_loaded('xdiff') ? 'xdiff' : 'native'; + } else { + $engine = basename($engine); + } + + global $script_path, $dir_separator; + require_once($script_path . 'diff' . $dir_separator . $engine . '.php'); + $class = 'Text_Diff_Engine_' . $engine; + $diff_engine = new $class(); + + $this->_edits = call_user_func_array(array($diff_engine, 'diff'), $params); + } + + /** + * Returns the array of differences. + */ + function getDiff() + { + return $this->_edits; + } + + /** + * returns the number of new (added) lines in a given diff. + * + * @since Text_Diff 1.1.0 + * @since Horde 3.2 + * + * @return integer The number of new lines + */ + function countAddedLines() + { + $count = 0; + foreach ($this->_edits as $edit) { + if (is_a($edit, 'Text_Diff_Op_add') || + is_a($edit, 'Text_Diff_Op_change')) { + $count += $edit->nfinal(); + } + } + return $count; + } + + /** + * Returns the number of deleted (removed) lines in a given diff. + * + * @since Text_Diff 1.1.0 + * @since Horde 3.2 + * + * @return integer The number of deleted lines + */ + function countDeletedLines() + { + $count = 0; + foreach ($this->_edits as $edit) { + if (is_a($edit, 'Text_Diff_Op_delete') || + is_a($edit, 'Text_Diff_Op_change')) { + $count += $edit->norig(); + } + } + return $count; + } + + /** + * Computes a reversed diff. + * + * Example: + * + * $diff = new Text_Diff($lines1, $lines2); + * $rev = $diff->reverse(); + * + * + * @return Text_Diff A Diff object representing the inverse of the + * original diff. Note that we purposely don't return a + * reference here, since this essentially is a clone() + * method. + */ + function reverse() + { + if (version_compare(zend_version(), '2', '>')) { + $rev = clone($this); + } else { + $rev = $this; + } + $rev->_edits = array(); + foreach ($this->_edits as $edit) { + $rev->_edits[] = $edit->reverse(); + } + return $rev; + } + + /** + * Checks for an empty diff. + * + * @return boolean True if two sequences were identical. + */ + function isEmpty() + { + foreach ($this->_edits as $edit) { + if (!is_a($edit, 'Text_Diff_Op_copy')) { + return false; + } + } + return true; + } + + /** + * Computes the length of the Longest Common Subsequence (LCS). + * + * This is mostly for diagnostic purposes. + * + * @return integer The length of the LCS. + */ + function lcs() + { + $lcs = 0; + foreach ($this->_edits as $edit) { + if (is_a($edit, 'Text_Diff_Op_copy')) { + $lcs += count($edit->orig); + } + } + return $lcs; + } + + /** + * Gets the original set of lines. + * + * This reconstructs the $from_lines parameter passed to the constructor. + * + * @return array The original sequence of strings. + */ + function getOriginal() + { + $lines = array(); + foreach ($this->_edits as $edit) { + if ($edit->orig) { + array_splice($lines, count($lines), 0, $edit->orig); + } + } + return $lines; + } + + /** + * Gets the final set of lines. + * + * This reconstructs the $to_lines parameter passed to the constructor. + * + * @return array The sequence of strings. + */ + function getFinal() + { + $lines = array(); + foreach ($this->_edits as $edit) { + if ($edit->final) { + array_splice($lines, count($lines), 0, $edit->final); + } + } + return $lines; + } + + /** + * Removes trailing newlines from a line of text. This is meant to be used + * with array_walk(). + * + * @param string $line The line to trim. + * @param integer $key The index of the line in the array. Not used. + */ + function trimNewlines(&$line, $key) + { + $line = str_replace(array("\n", "\r"), '', $line); + } + + /** + * Determines the location of the system temporary directory. + * + * @static + * + * @access protected + * + * @return string A directory name which can be used for temp files. + * Returns false if one could not be found. + */ + function _getTempDir() + { + $tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp', + 'c:\windows\temp', 'c:\winnt\temp'); + + /* Try PHP's upload_tmp_dir directive. */ + $tmp = ini_get('upload_tmp_dir'); + + /* Otherwise, try to determine the TMPDIR environment variable. */ + if (!strlen($tmp)) { + $tmp = getenv('TMPDIR'); + } + + /* If we still cannot determine a value, then cycle through a list of + * preset possibilities. */ + while (!strlen($tmp) && count($tmp_locations)) { + $tmp_check = array_shift($tmp_locations); + if (@is_dir($tmp_check)) { + $tmp = $tmp_check; + } + } + + /* If it is still empty, we have failed, so return false; otherwise + * return the directory determined. */ + return strlen($tmp) ? $tmp : false; + } + + /** + * Checks a diff for validity. + * + * This is here only for debugging purposes. + */ + function _check($from_lines, $to_lines) + { + if (serialize($from_lines) != serialize($this->getOriginal())) { + trigger_error("Reconstructed original doesn't match", E_USER_ERROR); + } + if (serialize($to_lines) != serialize($this->getFinal())) { + trigger_error("Reconstructed final doesn't match", E_USER_ERROR); + } + + $rev = $this->reverse(); + if (serialize($to_lines) != serialize($rev->getOriginal())) { + trigger_error("Reversed original doesn't match", E_USER_ERROR); + } + if (serialize($from_lines) != serialize($rev->getFinal())) { + trigger_error("Reversed final doesn't match", E_USER_ERROR); + } + + $prevtype = null; + foreach ($this->_edits as $edit) { + if ($prevtype == get_class($edit)) { + trigger_error("Edit sequence is non-optimal", E_USER_ERROR); + } + $prevtype = get_class($edit); + } + + return true; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + */ +class Text_MappedDiff extends Text_Diff { + + /** + * Computes a diff between sequences of strings. + * + * This can be used to compute things like case-insensitve diffs, or diffs + * which ignore changes in white-space. + * + * @param array $from_lines An array of strings. + * @param array $to_lines An array of strings. + * @param array $mapped_from_lines This array should have the same size + * number of elements as $from_lines. The + * elements in $mapped_from_lines and + * $mapped_to_lines are what is actually + * compared when computing the diff. + * @param array $mapped_to_lines This array should have the same number + * of elements as $to_lines. + */ + function Text_MappedDiff($from_lines, $to_lines, + $mapped_from_lines, $mapped_to_lines) + { + assert(count($from_lines) == count($mapped_from_lines)); + assert(count($to_lines) == count($mapped_to_lines)); + + parent::Text_Diff($mapped_from_lines, $mapped_to_lines); + + $xi = $yi = 0; + for ($i = 0; $i < count($this->_edits); $i++) { + $orig = &$this->_edits[$i]->orig; + if (is_array($orig)) { + $orig = array_slice($from_lines, $xi, count($orig)); + $xi += count($orig); + } + + $final = &$this->_edits[$i]->final; + if (is_array($final)) { + $final = array_slice($to_lines, $yi, count($final)); + $yi += count($final); + } + } + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op { + + var $orig; + var $final; + + function &reverse() + { + trigger_error('Abstract method', E_USER_ERROR); + } + + function norig() + { + return $this->orig ? count($this->orig) : 0; + } + + function nfinal() + { + return $this->final ? count($this->final) : 0; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op_copy extends Text_Diff_Op { + + function Text_Diff_Op_copy($orig, $final = false) + { + if (!is_array($final)) { + $final = $orig; + } + $this->orig = $orig; + $this->final = $final; + } + + function &reverse() + { + $reverse = &new Text_Diff_Op_copy($this->final, $this->orig); + return $reverse; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op_delete extends Text_Diff_Op { + + function Text_Diff_Op_delete($lines) + { + $this->orig = $lines; + $this->final = false; + } + + function &reverse() + { + $reverse = &new Text_Diff_Op_add($this->orig); + return $reverse; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op_add extends Text_Diff_Op { + + function Text_Diff_Op_add($lines) + { + $this->final = $lines; + $this->orig = false; + } + + function &reverse() + { + $reverse = &new Text_Diff_Op_delete($this->final); + return $reverse; + } + +} + +/** + * @package Text_Diff + * @author Geoffrey T. Dairiki + * + * @access private + */ +class Text_Diff_Op_change extends Text_Diff_Op { + + function Text_Diff_Op_change($orig, $final) + { + $this->orig = $orig; + $this->final = $final; + } + + function &reverse() + { + $reverse = &new Text_Diff_Op_change($this->final, $this->orig); + return $reverse; + } + +} diff --git a/diff/Renderer.php b/diff/Renderer.php new file mode 100644 index 0000000..db5a209 --- /dev/null +++ b/diff/Renderer.php @@ -0,0 +1,236 @@ + $value) { + $v = '_' . $param; + if (isset($this->$v)) { + $this->$v = $value; + } + } + } + + /** + * Get any renderer parameters. + * + * @return array All parameters of this renderer object. + */ + function getParams() + { + $params = array(); + foreach (get_object_vars($this) as $k => $v) { + if ($k[0] == '_') { + $params[substr($k, 1)] = $v; + } + } + + return $params; + } + + /** + * Renders a diff. + * + * @param Text_Diff $diff A Text_Diff object. + * + * @return string The formatted output. + */ + function render($diff) + { + $xi = $yi = 1; + $block = false; + $context = array(); + + $nlead = $this->_leading_context_lines; + $ntrail = $this->_trailing_context_lines; + + $output = $this->_startDiff(); + + $diffs = $diff->getDiff(); + foreach ($diffs as $i => $edit) { + /* If these are unchanged (copied) lines, and we want to keep + * leading or trailing context lines, extract them from the copy + * block. */ + if (is_a($edit, 'Text_Diff_Op_copy')) { + /* Do we have any diff blocks yet? */ + if (is_array($block)) { + /* How many lines to keep as context from the copy + * block. */ + $keep = $i == count($diffs) - 1 ? $ntrail : $nlead + $ntrail; + if (count($edit->orig) <= $keep) { + /* We have less lines in the block than we want for + * context => keep the whole block. */ + $block[] = $edit; + } else { + if ($ntrail) { + /* Create a new block with as many lines as we need + * for the trailing context. */ + $context = array_slice($edit->orig, 0, $ntrail); + $block[] = new Text_Diff_Op_copy($context); + } + /* @todo */ + $output .= $this->_block($x0, $ntrail + $xi - $x0, + $y0, $ntrail + $yi - $y0, + $block); + $block = false; + } + } + /* Keep the copy block as the context for the next block. */ + $context = $edit->orig; + } else { + /* Don't we have any diff blocks yet? */ + if (!is_array($block)) { + /* Extract context lines from the preceding copy block. */ + $context = array_slice($context, count($context) - $nlead); + $x0 = $xi - count($context); + $y0 = $yi - count($context); + $block = array(); + if ($context) { + $block[] = new Text_Diff_Op_copy($context); + } + } + $block[] = $edit; + } + + if ($edit->orig) { + $xi += count($edit->orig); + } + if ($edit->final) { + $yi += count($edit->final); + } + } + + if (is_array($block)) { + $output .= $this->_block($x0, $xi - $x0, + $y0, $yi - $y0, + $block); + } + + return $output . $this->_endDiff(); + } + + function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) + { + $output = $this->_startBlock($this->_blockHeader($xbeg, $xlen, $ybeg, $ylen)); + + foreach ($edits as $edit) { + switch (strtolower(get_class($edit))) { + case 'text_diff_op_copy': + $output .= $this->_context($edit->orig); + break; + + case 'text_diff_op_add': + $output .= $this->_added($edit->final); + break; + + case 'text_diff_op_delete': + $output .= $this->_deleted($edit->orig); + break; + + case 'text_diff_op_change': + $output .= $this->_changed($edit->orig, $edit->final); + break; + } + } + return $output . $this->_endBlock(); + } + + function _startDiff() + { + return ''; + } + + function _endDiff() + { + return ''; + } + + function _blockHeader($xbeg, $xlen, $ybeg, $ylen) + { + if ($xlen > 1) { + $xbeg .= ',' . ($xbeg + $xlen - 1); + } + if ($ylen > 1) { + $ybeg .= ',' . ($ybeg + $ylen - 1); + } + + // this matches the GNU Diff behaviour + if ($xlen && !$ylen) { + $ybeg--; + } elseif (!$xlen) { + $xbeg--; + } + + return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg; + } + + function _startBlock($header) + { + return $header . "\n"; + } + + function _endBlock() + { + return $this->_block_footer; + } + + function _lines($lines, $prefix = ' ') + { + return $prefix . implode("\n$prefix", $lines) . "\n"; + } + + function _context($lines) + { + return $this->_lines($lines, ' '); + } + + function _added($lines) + { + return $this->_lines($lines, '> '); + } + + function _deleted($lines) + { + return $this->_lines($lines, '< '); + } + + function _changed($orig, $final) + { + return $this->_deleted($orig) . "---\n" . $this->_added($final); + } + +} diff --git a/diff/inline.php b/diff/inline.php new file mode 100644 index 0000000..8eed190 --- /dev/null +++ b/diff/inline.php @@ -0,0 +1,177 @@ +'; + + /** + * Suffix for inserted text. + */ + var $_ins_suffix = ''; + + /** + * Prefix for deleted text. + */ + var $_del_prefix = ''; + + /** + * Suffix for deleted text. + */ + var $_del_suffix = ''; + + /** + * Header for each change block. + */ + var $_block_header = ''; + + /** + * Header for each change block. + */ + var $_block_footer = ''; + + /** + * What are we currently splitting on? Used to recurse to show word-level + * changes. + */ + var $_split_level = 'lines'; + + function _blockHeader($xbeg, $xlen, $ybeg, $ylen) + { + return $this->_block_header; + } + + function _startBlock($header) + { + return $header; + } + + function _lines($lines, $prefix = ' ', $encode = true) + { +// if ($encode) { +// array_walk($lines, array(&$this, '_encode')); +// } + + if ($this->_split_level == 'words') { + return implode('', $lines); + } else { + return implode("\n", $lines) . "\n"; + } + } + + function _added($lines) + { +// array_walk($lines, array(&$this, '_encode')); + $lines[0] = $this->_ins_prefix . $lines[0]; + $lines[count($lines) - 1] .= $this->_ins_suffix; + return $this->_lines($lines, ' ', false); + } + + function _deleted($lines, $words = false) + { +// array_walk($lines, array(&$this, '_encode')); + $lines[0] = $this->_del_prefix . $lines[0]; + $lines[count($lines) - 1] .= $this->_del_suffix; + return $this->_lines($lines, ' ', false); + } + + function _changed($orig, $final) + { + /* If we've already split on words, don't try to do so again - just + * display. */ + if ($this->_split_level == 'words') { + $prefix = ''; + while ($orig[0] !== false && $final[0] !== false && + substr($orig[0], 0, 1) == ' ' && + substr($final[0], 0, 1) == ' ') { + $prefix .= substr($orig[0], 0, 1); + $orig[0] = substr($orig[0], 1); + $final[0] = substr($final[0], 1); + } + return $prefix . $this->_deleted($orig) . $this->_added($final); + } + + $text1 = implode("\n", $orig); + $text2 = implode("\n", $final); + + /* Non-printing newline marker. */ + $nl = "\0"; + + /* We want to split on word boundaries, but we need to + * preserve whitespace as well. Therefore we split on words, + * but include all blocks of whitespace in the wordlist. */ + $diff = new Text_Diff('native', + array($this->_splitOnWords($text1, $nl), + $this->_splitOnWords($text2, $nl))); + + /* Get the diff in inline format. */ + $renderer = new Text_Diff_Renderer_inline + (array_merge($this->getParams(), + array('split_level' => 'words'))); + + /* Run the diff and get the output. */ + return str_replace($nl, "\n", $renderer->render($diff)) . "\n"; + } + + function _splitOnWords($string, $newlineEscape = "\n") + { + // Ignore \0; otherwise the while loop will never finish. + $string = str_replace("\0", '', $string); + + $words = array(); + $length = strlen($string); + $pos = 0; + + while ($pos < $length) { + // Eat a word with any preceding whitespace. + $spaces = strspn(substr($string, $pos), " \n"); + $nextpos = strcspn(substr($string, $pos + $spaces), " \n"); + $words[] = str_replace("\n", $newlineEscape, substr($string, $pos, $spaces + $nextpos)); + $pos += $spaces + $nextpos; + } + + return $words; + } + + function _encode(&$string) + { + // $string = htmlspecialchars($string); + } + +} diff --git a/diff/native.php b/diff/native.php new file mode 100644 index 0000000..84168c0 --- /dev/null +++ b/diff/native.php @@ -0,0 +1,438 @@ + 2, and some optimizations) are from + * Geoffrey T. Dairiki . The original PHP version of this + * code was written by him, and is used/adapted with his permission. + * + * $Horde: framework/Text_Diff/Diff/Engine/native.php,v 1.7.2.5 2009/01/06 15:23:41 jan Exp $ + * + * Copyright 2004-2009 The Horde Project (http://www.horde.org/) + * + * See the enclosed file COPYING for license information (LGPL). If you did + * not receive this file, see http://opensource.org/licenses/lgpl-license.php. + * + * @author Geoffrey T. Dairiki + * @package Text_Diff + */ +class Text_Diff_Engine_native { + + function diff($from_lines, $to_lines) + { + array_walk($from_lines, array('Text_Diff', 'trimNewlines')); + array_walk($to_lines, array('Text_Diff', 'trimNewlines')); + + $n_from = count($from_lines); + $n_to = count($to_lines); + + $this->xchanged = $this->ychanged = array(); + $this->xv = $this->yv = array(); + $this->xind = $this->yind = array(); + unset($this->seq); + unset($this->in_seq); + unset($this->lcs); + + // Skip leading common lines. + for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) { + if ($from_lines[$skip] !== $to_lines[$skip]) { + break; + } + $this->xchanged[$skip] = $this->ychanged[$skip] = false; + } + + // Skip trailing common lines. + $xi = $n_from; $yi = $n_to; + for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) { + if ($from_lines[$xi] !== $to_lines[$yi]) { + break; + } + $this->xchanged[$xi] = $this->ychanged[$yi] = false; + } + + // Ignore lines which do not exist in both files. + for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { + $xhash[$from_lines[$xi]] = 1; + } + for ($yi = $skip; $yi < $n_to - $endskip; $yi++) { + $line = $to_lines[$yi]; + if (($this->ychanged[$yi] = empty($xhash[$line]))) { + continue; + } + $yhash[$line] = 1; + $this->yv[] = $line; + $this->yind[] = $yi; + } + for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { + $line = $from_lines[$xi]; + if (($this->xchanged[$xi] = empty($yhash[$line]))) { + continue; + } + $this->xv[] = $line; + $this->xind[] = $xi; + } + + // Find the LCS. + $this->_compareseq(0, count($this->xv), 0, count($this->yv)); + + // Merge edits when possible. + $this->_shiftBoundaries($from_lines, $this->xchanged, $this->ychanged); + $this->_shiftBoundaries($to_lines, $this->ychanged, $this->xchanged); + + // Compute the edit operations. + $edits = array(); + $xi = $yi = 0; + while ($xi < $n_from || $yi < $n_to) { + assert($yi < $n_to || $this->xchanged[$xi]); + assert($xi < $n_from || $this->ychanged[$yi]); + + // Skip matching "snake". + $copy = array(); + while ($xi < $n_from && $yi < $n_to + && !$this->xchanged[$xi] && !$this->ychanged[$yi]) { + $copy[] = $from_lines[$xi++]; + ++$yi; + } + if ($copy) { + $edits[] = &new Text_Diff_Op_copy($copy); + } + + // Find deletes & adds. + $delete = array(); + while ($xi < $n_from && $this->xchanged[$xi]) { + $delete[] = $from_lines[$xi++]; + } + + $add = array(); + while ($yi < $n_to && $this->ychanged[$yi]) { + $add[] = $to_lines[$yi++]; + } + + if ($delete && $add) { + $edits[] = &new Text_Diff_Op_change($delete, $add); + } elseif ($delete) { + $edits[] = &new Text_Diff_Op_delete($delete); + } elseif ($add) { + $edits[] = &new Text_Diff_Op_add($add); + } + } + + return $edits; + } + + /** + * Divides the Largest Common Subsequence (LCS) of the sequences (XOFF, + * XLIM) and (YOFF, YLIM) into NCHUNKS approximately equally sized + * segments. + * + * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an array of + * NCHUNKS+1 (X, Y) indexes giving the diving points between sub + * sequences. The first sub-sequence is contained in (X0, X1), (Y0, Y1), + * the second in (X1, X2), (Y1, Y2) and so on. Note that (X0, Y0) == + * (XOFF, YOFF) and (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM). + * + * This function assumes that the first lines of the specified portions of + * the two files do not match, and likewise that the last lines do not + * match. The caller must trim matching lines from the beginning and end + * of the portions it is going to specify. + */ + function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) + { + $flip = false; + + if ($xlim - $xoff > $ylim - $yoff) { + /* Things seems faster (I'm not sure I understand why) when the + * shortest sequence is in X. */ + $flip = true; + list ($xoff, $xlim, $yoff, $ylim) + = array($yoff, $ylim, $xoff, $xlim); + } + + if ($flip) { + for ($i = $ylim - 1; $i >= $yoff; $i--) { + $ymatches[$this->xv[$i]][] = $i; + } + } else { + for ($i = $ylim - 1; $i >= $yoff; $i--) { + $ymatches[$this->yv[$i]][] = $i; + } + } + + $this->lcs = 0; + $this->seq[0]= $yoff - 1; + $this->in_seq = array(); + $ymids[0] = array(); + + $numer = $xlim - $xoff + $nchunks - 1; + $x = $xoff; + for ($chunk = 0; $chunk < $nchunks; $chunk++) { + if ($chunk > 0) { + for ($i = 0; $i <= $this->lcs; $i++) { + $ymids[$i][$chunk - 1] = $this->seq[$i]; + } + } + + $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $chunk) / $nchunks); + for (; $x < $x1; $x++) { + $line = $flip ? $this->yv[$x] : $this->xv[$x]; + if (empty($ymatches[$line])) { + continue; + } + $matches = $ymatches[$line]; + reset($matches); + while (list(, $y) = each($matches)) { + if (empty($this->in_seq[$y])) { + $k = $this->_lcsPos($y); + assert($k > 0); + $ymids[$k] = $ymids[$k - 1]; + break; + } + } + while (list(, $y) = each($matches)) { + if ($y > $this->seq[$k - 1]) { + assert($y <= $this->seq[$k]); + /* Optimization: this is a common case: next match is + * just replacing previous match. */ + $this->in_seq[$this->seq[$k]] = false; + $this->seq[$k] = $y; + $this->in_seq[$y] = 1; + } elseif (empty($this->in_seq[$y])) { + $k = $this->_lcsPos($y); + assert($k > 0); + $ymids[$k] = $ymids[$k - 1]; + } + } + } + } + + $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff); + $ymid = $ymids[$this->lcs]; + for ($n = 0; $n < $nchunks - 1; $n++) { + $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks); + $y1 = $ymid[$n] + 1; + $seps[] = $flip ? array($y1, $x1) : array($x1, $y1); + } + $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim); + + return array($this->lcs, $seps); + } + + function _lcsPos($ypos) + { + $end = $this->lcs; + if ($end == 0 || $ypos > $this->seq[$end]) { + $this->seq[++$this->lcs] = $ypos; + $this->in_seq[$ypos] = 1; + return $this->lcs; + } + + $beg = 1; + while ($beg < $end) { + $mid = (int)(($beg + $end) / 2); + if ($ypos > $this->seq[$mid]) { + $beg = $mid + 1; + } else { + $end = $mid; + } + } + + assert($ypos != $this->seq[$end]); + + $this->in_seq[$this->seq[$end]] = false; + $this->seq[$end] = $ypos; + $this->in_seq[$ypos] = 1; + return $end; + } + + /** + * Finds LCS of two sequences. + * + * The results are recorded in the vectors $this->{x,y}changed[], by + * storing a 1 in the element for each line that is an insertion or + * deletion (ie. is not in the LCS). + * + * The subsequence of file 0 is (XOFF, XLIM) and likewise for file 1. + * + * Note that XLIM, YLIM are exclusive bounds. All line numbers are + * origin-0 and discarded lines are not counted. + */ + function _compareseq ($xoff, $xlim, $yoff, $ylim) + { + /* Slide down the bottom initial diagonal. */ + while ($xoff < $xlim && $yoff < $ylim + && $this->xv[$xoff] == $this->yv[$yoff]) { + ++$xoff; + ++$yoff; + } + + /* Slide up the top initial diagonal. */ + while ($xlim > $xoff && $ylim > $yoff + && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) { + --$xlim; + --$ylim; + } + + if ($xoff == $xlim || $yoff == $ylim) { + $lcs = 0; + } else { + /* This is ad hoc but seems to work well. $nchunks = + * sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); $nchunks = + * max(2,min(8,(int)$nchunks)); */ + $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1; + list($lcs, $seps) + = $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks); + } + + if ($lcs == 0) { + /* X and Y sequences have no common subsequence: mark all + * changed. */ + while ($yoff < $ylim) { + $this->ychanged[$this->yind[$yoff++]] = 1; + } + while ($xoff < $xlim) { + $this->xchanged[$this->xind[$xoff++]] = 1; + } + } else { + /* Use the partitions to split this problem into subproblems. */ + reset($seps); + $pt1 = $seps[0]; + while ($pt2 = next($seps)) { + $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]); + $pt1 = $pt2; + } + } + } + + /** + * Adjusts inserts/deletes of identical lines to join changes as much as + * possible. + * + * We do something when a run of changed lines include a line at one end + * and has an excluded, identical line at the other. We are free to + * choose which identical line is included. `compareseq' usually chooses + * the one at the beginning, but usually it is cleaner to consider the + * following identical line to be the "change". + * + * This is extracted verbatim from analyze.c (GNU diffutils-2.7). + */ + function _shiftBoundaries($lines, &$changed, $other_changed) + { + $i = 0; + $j = 0; + + assert('count($lines) == count($changed)'); + $len = count($lines); + $other_len = count($other_changed); + + while (1) { + /* Scan forward to find the beginning of another run of + * changes. Also keep track of the corresponding point in the + * other file. + * + * Throughout this code, $i and $j are adjusted together so that + * the first $i elements of $changed and the first $j elements of + * $other_changed both contain the same number of zeros (unchanged + * lines). + * + * Furthermore, $j is always kept so that $j == $other_len or + * $other_changed[$j] == false. */ + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + + while ($i < $len && ! $changed[$i]) { + assert('$j < $other_len && ! $other_changed[$j]'); + $i++; $j++; + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + } + + if ($i == $len) { + break; + } + + $start = $i; + + /* Find the end of this run of changes. */ + while (++$i < $len && $changed[$i]) { + continue; + } + + do { + /* Record the length of this run of changes, so that we can + * later determine whether the run has grown. */ + $runlength = $i - $start; + + /* Move the changed region back, so long as the previous + * unchanged line matches the last changed one. This merges + * with previous changed regions. */ + while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) { + $changed[--$start] = 1; + $changed[--$i] = false; + while ($start > 0 && $changed[$start - 1]) { + $start--; + } + assert('$j > 0'); + while ($other_changed[--$j]) { + continue; + } + assert('$j >= 0 && !$other_changed[$j]'); + } + + /* Set CORRESPONDING to the end of the changed run, at the + * last point where it corresponds to a changed run in the + * other file. CORRESPONDING == LEN means no such point has + * been found. */ + $corresponding = $j < $other_len ? $i : $len; + + /* Move the changed region forward, so long as the first + * changed line matches the following unchanged one. This + * merges with following changed regions. Do this second, so + * that if there are no merges, the changed region is moved + * forward as far as possible. */ + while ($i < $len && $lines[$start] == $lines[$i]) { + $changed[$start++] = false; + $changed[$i++] = 1; + while ($i < $len && $changed[$i]) { + $i++; + } + + assert('$j < $other_len && ! $other_changed[$j]'); + $j++; + if ($j < $other_len && $other_changed[$j]) { + $corresponding = $i; + while ($j < $other_len && $other_changed[$j]) { + $j++; + } + } + } + } while ($runlength != $i - $start); + + /* If possible, move the fully-merged run of changes back to a + * corresponding run in the other file. */ + while ($corresponding < $i) { + $changed[--$start] = 1; + $changed[--$i] = 0; + assert('$j > 0'); + while ($other_changed[--$j]) { + continue; + } + assert('$j >= 0 && !$other_changed[$j]'); + } + } + } + +} diff --git a/functions.php b/functions.php new file mode 100644 index 0000000..1655e07 --- /dev/null +++ b/functions.php @@ -0,0 +1,145 @@ + $value) + { + switch($value) + { + case '-o': + case '--old': + $args['old'] = $argv[$key + 1]; + break; + + case '-n': + case '--new': + $args['new'] = $argv[$key + 1]; + break; + + case '-f': + case '--outfile': + $args['outfile'] = $argv[$key + 1]; + break; + + case '-v': + case '--verbose': + $args['verbose'] = true; + break; + + case '-h': + case '--help': + $args['help'] = true; + break; + + case '-c': + case '--custom': + $args['diff_opt'] = DIFF_CUSTOM; + break; + + default: + continue; + break; + } + } + return($args); +} + +/** + * Checks the directory arrays for missing files in $old_dir and writes a copy-tag if files are missing. + */ +function check_missing($old_arr, $new_arr) +{ + global $xml, $where_changes; + + $missing = false; + + foreach ($new_arr as $file) + { + if (!in_array($file, $old_arr)) + { + if (!$missing) + { + $missing = true; + $where_changes = true; + $xml->startElement('copy'); + } + // On Windows the directory separator will be \, so we need to replace that. + $file = str_replace('\\', '/', $file); + $xml->write_element('file', '', array('from' => 'root/' . $file, 'to' => $file)); + } + } + if ($missing) + { + $xml->endElement(); + } +} + +/** + * Sorts the directory in alphabetical order, files first. + */ +function directory_sort($dir) +{ + $filenames = $directories = $files = array(); + foreach ($dir as $key => $value) + { + $files[$key] = $value; + $filenames[$key] = basename($value); + $directories[$key] = dirname($value); + } + array_multisort($directories, SORT_STRING, $filenames, SORT_STRING, $files); + + return($files); +} + +/** + * Reads a directory recursive and puts the result in a array. + * From evil<3s diff_tools + * Slightly modified. + */ +function get_dir_contents($dir, &$dir_arr, $base = '') +{ + global $ignore, $args, $dir_separator; + + $ignore = array_merge(array('.', '..'), $ignore); + + $handle = opendir($dir); + while (($file = readdir($handle)) !== false) + { + if (!in_array($file, $ignore)) + { + $path = $dir . $dir_separator . $file; + if ($args['diff_opt'] == DIFF_BASIC && is_dir($path)) + { + // Only diff Prosilver and English + // Other styles and languages require their own install files. + if ((basename($dir) == 'styles' && $file != 'prosilver') || (basename($dir) == 'language' && $file != 'en')) + { + continue; + } + } + if (is_file($path)) + { + $dir_arr[] = $base . $file; + } + else if (is_dir($path)) + { + get_dir_contents($path, $dir_arr, $base . $file . $dir_separator); + } + } + } + closedir($handle); +} diff --git a/modx_gen.php b/modx_gen.php new file mode 100644 index 0000000..3b84232 --- /dev/null +++ b/modx_gen.php @@ -0,0 +1,212 @@ +render($diff); + unset($renderer, $diff); + + $parser = new parse_diff(); + $file_diff = $parser->parse($file_diff); + + if (!empty($file_diff)) + { + $xml = new modx_writer(); + + $where_changes = true; + $xml->generate_xml($file, $file_diff); + } +} +else +{ + // Add / to the end of the paths if it's not already there + $args['old'] .= (substr($args['old'], -1) != $dir_separator) ? $dir_separator : ''; + $args['new'] .= (substr($args['new'], -1) != $dir_separator) ? $dir_separator : ''; + + // Get the files + if ($args['verbose']) + { + echo 'Getting files' . "\n"; + } + get_dir_contents($args['old'], $old_arr); + get_dir_contents($args['new'], $new_arr); + + // Sort them alphabetically + if ($args['verbose']) + { + echo 'Sorting files' . "\n"; + } + $old_arr = directory_sort($old_arr); + $new_arr = directory_sort($new_arr); + + $xml = new modx_writer(); + $parser = new parse_diff(); + + // Start with a check for new files + if ($args['verbose']) + { + echo 'Checking for missing files' . "\n"; + } + check_missing($old_arr, $new_arr); + + foreach ($old_arr as $file) + { + $ext = substr(strrchr($file, '.'), 1); + + if (in_array($ext, $ignore_ext) || !file_exists($args['new'] . $file)) + { + continue; + } + if ($args['verbose']) + { + echo 'Comparing file: ' . $file; + } + + $old_file = file($args['old'] . $file); + $new_file = file($args['new'] . $file); + + if ($old_file != $new_file) + { + if (filesize($args['old'] . $file) == 0) + { + echo $args['old'] . $file . ' is empty, can\'t create a find in an empty file.' . "\n"; + continue; + } + + if ($args['verbose']) + { + echo '... Differences found.' . "\n"; + } + + $diff = new Text_Diff('native', array($old_file, $new_file)); + unset($old_file, $new_file); + + $renderer = new Text_Diff_Renderer_inline(); + $file_diff = $renderer->render($diff); + unset($renderer, $diff); + + $file_diff = $parser->parse($file_diff); + + if ($file_diff) + { + $where_changes = true; + $xml->generate_xml($file, $file_diff); + } + } + else if ($args['verbose']) + { + echo '... Identical.' . "\n"; + } + } +} + +if (isset($xml) && $where_changes) +{ + $out_file = (isset($args['outfile'])) ? $args['outfile'] : ''; + $xml->modx_close($out_file); +} + +// Should be removed before final release. +echo 'Memory peak: ' . memory_get_peak_usage(true) . "\n"; +$mtime = microtime(); +$mtime = explode(" ",$mtime); +$mtime = $mtime[1] + $mtime[0]; +$endtime = $mtime; +$totaltime = ($endtime - $starttime); +echo 'Execution time: ' . $totaltime . ' seconds' . "\n"; \ No newline at end of file diff --git a/modx_writer.php b/modx_writer.php new file mode 100644 index 0000000..8fccb64 --- /dev/null +++ b/modx_writer.php @@ -0,0 +1,225 @@ +openMemory(); + $this->setIndent(true); + $this->setIndentString("\t"); + + // The header + $this->startDocument('1.0', 'UTF-8', 'yes'); + $this->writePi('xml-stylesheet', 'type="text/xsl" href="modx.prosilver.en.xsl"'); + $this->writeComment('NOTICE: Please open this file in your web browser. If presented with a security warning, you may safely tell it to allow the blocked content.'); + $this->writeComment('For security purposes, please check: http://www.phpbb.com/mods/ for the latest version of this MOD.\nAlthough MODs are checked before being allowed in the MODs Database there is no guarantee that there are no security problems within the MOD.\nNo support will be given for MODs not found within the MODs Database which can be found at http://www.phpbb.com/mods/'); + + // + $this->startElement('mod'); + $this->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + $this->writeAttribute('xmlns', 'http://www.phpbb.com/mods/xml/modx-1.2.3.xsd'); + + //
+ $this->startElement('header'); + + // + $this->write_element('meta', '', array( + 'name' => 'generator', + 'content' => 'MODX file generated by MODX Diff', + ), false, false); + + //
+ $this->endElement(); + $this->startElement('action-group'); + } + + /** + * Writes the edits to xml + * + * @param $name, the tag name. + * @param $text, text for the tag. + * @param $attributes, attributes if the are any. + */ + public function write_element($name, $text, $attributes = false) + { + if ($text == '' && $attributes == false) + { + // nothing to write + return; + } + + $this->startElement($name); + if ($attributes != false) + { + foreach ($attributes as $key => $value) + { + if ($value != '') + { + $this->writeAttribute($key, $value); + } + } + } + if ($text != '') + { + // We need to check for in the strings. + // Accoring to DavidIQ this should work. + // Can't use a regular expresion for this, there might be only ]]> in the files. + $find = array( + '', + '<![CDATA[', + ']]>'); + $replace = array( + '<![CDATA[', + ']]>', + ']]><![CDATA[]]>writeCdata($text); + } + $this->endElement(); + } + + /** + * Write the diff to the modx file. + * + * @param $file, file name. + * @param $file_diff, the famous diff- + */ + public function generate_xml($file, $file_diff) + { + $last_change = 0; + + // On Windows the directory separator will be \, so we need to replace that. + $file = str_replace('\\', '/', $file); + + $this->startElement('open'); + $this->writeAttribute('src', $file); + + foreach ($file_diff as $line => $value) + { + if (is_array($value)) + { + if (isset($value['find'])) + { + $this->startElement('edit'); + + // Both inlines and normal edits needs to start with a FIND + $this->write_element('find', $value['find'][0]); + if (isset($value['find'][1])) + { + $this->write_element('find', $value['find'][1]); + } + } + + if ($value['type'] == INLINE) + { + // Inline edit + foreach ($value['changes'] as $change) + { + switch($change['add-type']) + { + case ADD_BEFORE: + $change_type = 'before-add'; + break; + + case REPLACE: + $change_type = 'replace-with'; + break; + + default: + $change_type = 'after-add'; + break; + } + if(isset($change['inline-find'])) + { + $this->startElement('inline-edit'); + $this->write_element('inline-find', $change['inline-find']); + } + $this->write_element('inline-action', $change['add'], array('type' => $change_type)); + if(isset($change['close'])) + { + $this->endElement(); + } + } + } + else if ($value['type'] == EDIT) + { + // Edit + if (isset($value['add'])) + { + switch($value['add-type']) + { + case ADD_BEFORE: + $change_type = 'before-add'; + break; + + case REPLACE: + $change_type = 'replace-with'; + break; + + default: + $change_type = 'after-add'; + break; + } + $this->write_element('action', $value['add'], array('type' => $change_type)); + } + else if (!empty($value['del'])) + { + $this->write_element('action', '', array('type' => 'replace-with')); + } + } + else + { + // Eh? + } + + if (isset($value['close'])) + { + $this->endElement(); + } + } + } + + $this->endElement(); + } + + /** + * Closes the file and either returns the modx or writes it to file + */ + public function modx_close($out_file = '') + { + $this->endElement(); + $this->endElement(); + + $out_string = $this->outputMemory(); + + if ($out_file) + { + file_put_contents($out_file, $out_string); + } + else + { + echo $out_string . "\n"; + } + } + +} + +?> \ No newline at end of file diff --git a/parse_diff.php b/parse_diff.php new file mode 100644 index 0000000..5b35c17 --- /dev/null +++ b/parse_diff.php @@ -0,0 +1,1035 @@ +render($diff)); + */ +class parse_diff +{ + /** + * The chars that serparate words. + * These will be used for the in-line edits. + * Need to figure out what chars should be counted as separators. + */ + var $separator = array( + ' ', // Space + ' ', // tab + '(', + ')', + '[', + ']', + '{', + '}', + '->', + '<', + '>', + '\'', + '"', + ',', + '.', + ';', + '!', + '\\', + '/', + '=', + '?', + '@', +// '$', +// '_', + ); + /** + * Runs the diff + * + * @param $diff, the raw diff from Text_diff. + * @param $f, string, the file to diff, will be removed before release. + */ + public function parse($diff, $f = '') + { + if (!empty($f)) + { + $this->file = $f; + } + + // We need a array to parse + $file_diff = explode("\n", $diff); + + // Send the diff for the first run + $file_diff = $this->parse_diff_first_pass($file_diff); + + // And the second run + $file_diff = $this->parse_diff_second_pass($file_diff); + + return($file_diff); + } + + /** + * parse_diff_first_pass + * Parse the diff first run + * + * @param $file_diff, array, the raw diff. + * @return $diff_arr, array, contains the parsed diff for the next run. + */ + private function parse_diff_first_pass($file_diff) + { + // A temporary array for the diff + $diff_arr = array(); + + $end = count($file_diff); + // The first and last thing in the array is and . + // Let's remove them, they will only confuse later. + if (substr($file_diff[0], 0, 13) == '') + { + $file_diff[0] = substr($file_diff[0], 13); + } + $key = $end - 1; + $len = strlen($file_diff[$key]); + if ($len >= 14) + { + if (substr($file_diff[$key], $len - 14) == '') + { + $file_diff[$key] = substr($file_diff[$key], 0, $len - 14); + } + } + + // Let's step trough the array and arrange it to something more handy. + $cnt = 0; + + for ($key = 0; $key < $end; $key++) + { + if (strpos($file_diff[$key], '') !== false) + { + // This is a change with possible inline edits. Let's find out. + // Start by turning it back to a string. + $str = $file_diff[$key]; + while (strpos($file_diff[$key], '') === false) + { + $str .= "\n" . $file_diff[++$key]; + if ($key >= $end) + { + break; + } + } + // Strip and + $str = $this->strip_tag_group($str, 'modx-change'); + // Get the original and changed lines. + $orig = $this->rem_tag_data($str, 'modx-add'); + $orig = $this->strip_tag_group($orig, 'modx-del'); + $new = $this->rem_tag_data($str, 'modx-del'); + $new = $this->strip_tag_group($new, 'modx-add'); + + // Now explode them with the new and old separated. + $orig_arr = explode("\n", $orig); + $new_arr = explode("\n", $new); + $orig_size = sizeof($orig_arr); + $new_size = sizeof($new_arr); + + if ($orig_size == $new_size) + { + // We have equal number of lines. Mostly one. + for ($i = 0; $i < $orig_size; $i++) + { + if (trim($orig_arr[$i]) == trim($new_arr[$i])) + { + // We don't care about leading or trailing whitespace changes. + $diff_arr[$cnt] = $orig_arr[$i]; + } + else if (substr(trim($orig_arr[$i]), 0, 1) == '*' && substr(trim($new_arr[$i]), 0, 1) == '*' || (substr(trim($orig_arr[$i]), 0, 2) == '//' && substr(trim($new_arr[$i]), 0, 2) == '//')) + { + // If the line starts with * or // we don't care about inline stuff. Just replace the whole line. + // These lines are typically comments or file headers. + $diff_arr[$cnt]['del'] = $orig_arr[$i]; + $diff_arr[$cnt]['add'] = $new_arr[$i]; + $diff_arr[$cnt]['type'] = EDIT; + } + else + { + // These are true inlines. Lets save them for the next run. + $diff_arr[$cnt]['del'] = $orig_arr[$i]; + $diff_arr[$cnt]['add'] = $new_arr[$i]; + $diff_arr[$cnt]['type'] = INLINE; + } + $cnt++; + } + } + else if ($new_size && $orig_size && $new_size > $orig_size) + { + + // Contains both in-line edits and add-after or add-before. + // Let's start with guessing which are most likely the in-lines. + $inlines = array(); + $prev_hit = -1; + for ($i = 0; $i < $orig_size; $i++) + { + // The first edit can't be matched with the last if there are more to come. + $preserved = $new_size - ($orig_size - $i - 1); + $hit = $top_proc = 0; + foreach ($new_arr as $line => $value) + { + // No need to check preserved lines. + if ($line >= $preserved) + { + break; + } + // $precent is the difference between the lines. + $percent = similar_text($orig_arr[$i], $value); + + // $top_proc contains the highest match for this line so far. So $percent must be higher for $hit to change. + // $prev_hit contains the last match so the inline edits comes in the right order. + // $preserved contains the number of lines that must be preserved for the edits to come. The first edit can't match with the last line + $hit = ($percent > $top_proc && $line > $prev_hit && $line < $preserved) ? $line : $hit; + // Can't fill $top_proc before the previous hit is passed. + $top_proc = ($line > $prev_hit) ? (($percent > $top_proc) ? $percent : $top_proc) : 0; + } + + // If we didn't get any hits on this one let's put it in the last possible place. Don't ask why. + $hit = (!$hit && !$top_proc) ? $preserved - 1 : $hit; + + $inlines[$i] = $hit; + $prev_hit = $hit; + } + unset($prev_hit, $preserved, $hit, $top_proc, $line, $value, $percent); + // Got the inlines. Now put them in the right places... + $j = 0; + $cnt--; + $in_edit = false; + + for ($i = 0; $i < $new_size; $i++) + { + if (isset($inlines[$j]) && $inlines[$j] == $i) + { + $cnt++; + if (isset($new_arr[$i]) && isset($orig_arr[$j]) && trim($orig_arr[$j]) != trim($new_arr[$i])) + { + $diff_arr[$cnt]['del'] = $orig_arr[$j++]; + $diff_arr[$cnt]['add'] = $new_arr[$i]; + $diff_arr[$cnt]['type'] = INLINE; + } + else + { + $diff_arr[$cnt] = $orig_arr[$j++]; + } + $in_edit = false; + } + else + { + if (!$in_edit) + { + $cnt++; + $diff_arr[$cnt]['type'] = EDIT; + $diff_arr[$cnt]['add'] = ''; + $in_edit = true; + } + $diff_arr[$cnt]['add'] .= (($diff_arr[$cnt]['add'] == '') ? '' : "\n") . $new_arr[$i]; + } + } + + $cnt++; + } + else if ($new_size && $orig_size && $new_size < $orig_size) + { + // Contains both in-line edits and lines to delete. + // We need to guess the in-lines. + $inlines = array(); + $prev_hit = 0; + for ($i = 0; $i < $new_size; $i++) + { + // $orig_arr[] will have more lines than $new_arr[] + // We need to save space for all in-lines. + $preserved = $orig_size - ($new_size - $i - 1); + $hit = $top_proc = 0; + foreach ($orig_arr as $line => $value) + { + // No need to check preserved lines. + if ($line >= $preserved) + { + break; + } + $percent = similar_text($new_arr[$i], $value); + + // $top_proc contains the highest match for this line so far. So $percent must be higher for $hit to change. + // $prev_hit contains the last match so the inline edits comes in the right order. + // $preserved contains the number of lines that must be preserved for the edits to come. The first edit can't match with the last line + $hit = ($percent > $top_proc && $line > $prev_hit && $line < $preserved) ? $line : $hit; + + // Can't fill $top_proc before the previous hit is passed. + $top_proc = ($line > $prev_hit) ? (($percent > $top_proc) ? $percent : $top_proc) : 0; + } + $hit = (!$hit && !$top_proc) ? $preserved - 1 : $hit; + $inlines[$i] = $hit; + $prev_hit = $hit; + } + unset($prev_hit, $preserved, $hit, $top_proc, $line, $value, $percent); + // Got the inlines. Now put them in the right places... + $j = 0; + $cnt--; + $in_edit = false; + for ($i = 0; $i < $orig_size; $i++) + { + if (isset($inlines[$j]) && $inlines[$j] == $i) + { + $cnt++; + if (isset($new_arr[$j]) && isset($orig_arr[$i]) && trim($orig_arr[$i]) != trim($new_arr[$j])) + { + $diff_arr[$cnt]['del'] = $orig_arr[$i]; + $diff_arr[$cnt]['add'] = $new_arr[$j++]; + $diff_arr[$cnt]['type'] = INLINE; + } + else + { + $diff_arr[$cnt] = $orig_arr[$i]; + } + $in_edit = false; + } + else + { + if (!$in_edit) + { + $cnt++; + $diff_arr[$cnt]['type'] = EDIT; + $diff_arr[$cnt]['del'] = ''; + $in_edit = true; + } + $diff_arr[$cnt]['del'] .= (($diff_arr[$cnt]['del'] == '') ? '' : "\n") . $orig_arr[$i]; + } + + } + $cnt++; + } + } + + else if (strpos($file_diff[$key], '') !== false) + { + // These are simple adds, just needs to be copied to the diff_arr + $diff_arr[$cnt] = array(); + $diff_arr[$cnt]['type'] = EDIT; + $diff_arr[$cnt]['add'] = $file_diff[$key]; + while (strpos($file_diff[$key], '') === false) + { + $diff_arr[$cnt]['add'] .= "\n" . $file_diff[++$key]; + if ($key >= $end) + { + break; + } + } + // Strip and + $diff_arr[$cnt]['add'] = $this->strip_tag_group($diff_arr[$cnt]['add'], 'modx-add'); + $cnt++; + } + + else if (strpos($file_diff[$key], '') !== false) + { + // These are deletes. Lines to remove. + // They usually stops in the in-line section but some might end up here. + $diff_arr[$cnt] = array(); + $diff_arr[$cnt]['type'] = EDIT; + $diff_arr[$cnt]['del'] = $file_diff[$key]; + while (strpos($file_diff[$key], '') === false) + { + $diff_arr[$cnt]['del'] .= "\n" . $file_diff[++$key]; + if ($key >= $end) + { + break; + } + } + // Strip and + $diff_arr[$cnt]['del'] = $this->strip_tag_group($diff_arr[$cnt]['del'], 'modx-del'); + $cnt++; + } + + else + { + // Unchanged lines. Needed later for the finds. + $diff_arr[$cnt++] = $file_diff[$key]; + } + } + + return($diff_arr); + } + + /** + * parse_diff_second_pass + * Parse the diff a second time. + * @param $file_diff, array containing the diff to parse. + * @return $file_diff, array the diff ready to be written. + */ + private function parse_diff_second_pass($file_diff) + { + $last_change = -1; + $find = ''; + + // Some of the inlines might need to be converted to normal edits. + $file_diff = $this->check_inlines($file_diff); + + foreach ($file_diff as $num => &$row) + { + // Let's make sure this element has not been removed. + if(!isset($row)) + { + continue; + } + // If there is any changes it's a array. Otherwise a string. + if (is_array($row) && empty($row['add-type'])) + { + if (empty($row['add']) && empty($row['del'])) + { + // Some edits only wants to add or remove a newline. Let's ignore them. + if (isset($row['add'])) + { + // Where adding a LF, just remove the element + unset($file_diff[$num]); + } + if (isset($row['del'])) + { + // Someone wants to remove a newline. We might need it for a find. + unset($file_diff[$num]); + $file_diff[$num] = ''; + } + continue; + } + + // These are either INLINE or EDIT. + if ($row['type'] == INLINE) + { + // All inlines have both del and add set. + $this->gen_find($file_diff, $num, $last_change, $row['find'], $row['del']); + + // $num_edits is not used now. There was a plan so I'll leave it for now it the plan returns. + // $row['changes'] contains all in-line edits for this line. + $num_edits = $this->gen_inline_find($row['del'], $row['add'], $row['changes']); + + // Need to keep track of the last change for the finds. + $last_change = $num; + } + else if ($row['type'] == EDIT) + { + if (!empty($row['add']) && !empty($row['del'])) + { + // These should only be comments + // All comments gets replaced. We don't care about inline stuff for them. + $row['add-type'] = REPLACE; + $row['find'][0] = $row['del']; + } + else + { + // Edits have only add or del set. + // If this is a del it might just be a move to the other side of a LF + if (!empty($row['del'])) + { + // Let's check to be sure. + $i = $num + 1; + while ($file_diff[$i] == '') + { + $i++; + } + if (!empty($file_diff[$i]['add']) && $file_diff[$i]['add'] == $row['del']) + { + // They are identical. Only a LF that's in the wrong place + // We'll ignore this. Place back the old and remove the new. + $old_string = $row['del']; + unset($file_diff[$i], $file_diff[$num]); + $file_diff[$num] = $old_string; + continue; + } + } + + if (empty($row['add']) && !empty($row['del'])) + { + // This is a delete. We need to pass the deleted string to gen_find. + $row['add-type'] = $this->gen_find($file_diff, $num, $last_change, $row['find'], $row['del']); + } + else + { + $row['add-type'] = $this->gen_find($file_diff, $num, $last_change, $row['find']); + } + if ($row['find'][0] == chr(0)) + { + unset($row['find']); + } + } + $last_change = $num; + } + else + { + // Huh? + // Should be imposible to get here. But if somebody succeeds, I want to hear about it. + echo 'Tell somebody you got here' . "\n"; + } + } + } + unset($num, $row); + + // There might be some deleted keys so lets get them in order again. + $file_diff = $this->reset_keys($file_diff); + + $file_diff = $this->mark_finds($file_diff); + + return($file_diff); + } + + /** + * check_inlines + * + * Converts some in-lines to normal edits. + * In-lines resulting in a commet or where both old and new are comments gets converted. + * In-lines where old only contains whitespace needs also to be converted. + */ + private function check_inlines($file_diff) + { + $diff_arr = array(); + $cnt = 0; + foreach ($file_diff as $key => $row) + { + // We'll only check in-lines. + if (is_array($row) && $row['type'] == INLINE) + { + $temp_add = trim($row['add']); + $temp_del = trim($row['del']); + + // With comments the whole line gets replaced. No inline for them. + if (substr($temp_add, 0, 1) == '*' || substr($temp_add, 0, 2) == '//') + { + $row['type'] = EDIT; + $diff_arr[$cnt++] = $row; + } + + // We make in-line edits where the find only contains whitespace to a edit. + // There will not be anything in the line to in-line find. + else if ($temp_del == '') + { + // We'll put the new line first + $diff_arr[$cnt]['type'] = EDIT; + $diff_arr[$cnt]['add'] = $row['add']; + $cnt++; + + // The old line needs also to be there + $diff_arr[$cnt++] = $row['del']; + } + else + { + $diff_arr[$cnt++] = $row; + } + } + else + { + $diff_arr[$cnt++] = $row; + } + unset($file_diff[$key]); + } + + return($diff_arr); + } + + /** + * Resets the keys in a array to get rid off missing keys. + * + * @param $arr, array to reset. + */ + private function reset_keys($arr) + { + $temp_arr = array(); + + $end = sizeof($arr); + for ($i = 0, $j = 0; $i < $end; $i++) + { + if (isset($arr[$i])) + { + $temp_arr[$j++] = $arr[$i]; + } + } + return($temp_arr); + } + + /** + * strip_tags + * + * Strips unvanted stuff from fields... + * , and so on. + * @param $data, string or array, what to remove tags from. + * @param $tag, string, the tag to remove. + * @return $data, string, with the tag removed. + */ + private function strip_tag_group($data, $tag) + { + $data = preg_replace('<<' . $tag . '>>', '', $data); + $data = preg_replace('<>', '', $data); + return($data); + } + + /** + * rem_tag_data + * + * Removes tags and their data + * @param $data, string or array, what to remove tags and data from. + * @param $tag, string, the tag to remove. + * @return $data, string, with the tag and data removed. + */ + private function rem_tag_data($data, $tag) + { + $data = preg_replace('/<' . $tag . '\b[^>]*>(.*?)<\/' . $tag . '>/s', '', $data); + return($data); + } + + /** + * gen_find + * Generate the finds + * @param $file_diff, array, the diff to get the finds from. + * @param $num, int, the line number. + * @param $last_change, int, the linenumber for the last change, can't use that for our find. + * @param $find, array, the array to put the finds in. + * @param $inline, string, if this is a inline edit this contains the target line. We'll add it to its own find. + * @return $return, int. Is it add-after or add-before (if not in-line)? + */ + private function gen_find(&$file_diff, $num, $last_change, &$find, $inline = false) + { + $find = array(); + $find[0] = ''; + $rows = $return = 0; + + // $search_before = ($num - $last_change > 1) ? true : false; + // Should this be a add-after or before. + $search_before = ($num > 0) ? true : false; + + // With deletes and in-line edits we always need to search befor the edit. + $search_before = ($inline) ? true : $search_before; + + if ($search_before) + { + // This is a add after. + for ($i = $num - 1; $i > $last_change; $i--) + { + if ((isset($file_diff[$i]) && !is_string($file_diff[$i])) || !isset($file_diff[$i]) || $rows > SEARCH_ROWS - 1) + { + break; + } + $rows++; + + $find[0] = $file_diff[$i] . (($find[0] == '') ? '' : "\n") . $find[0]; + } + $return = ADD_AFTER; + } + + if ($inline) + { + // If it's a inline edit we add the line in its own find. + // That way we can be sure that the find starts in the right line. + $i = (empty($find[0])) ? 0 : 1; + $find[$i] = $inline; + $rows = ($i == 1) ? SEARCH_ROWS : $rows + 1; + } + + if (!$search_before) // || ($inline && $rows < SEARCH_ROWS)) + { + // A add-before + for ($i = $num + 1, $end = $num + 4; $i < $end; $i++) + { + if ((isset($file_diff[$i]) && !is_string($file_diff[$i])) || !isset($file_diff[$i]) || $rows > SEARCH_ROWS - 1) + { + break; + } + $rows++; + $find[0] .= (($find[0] == '') ? '' : "\n") . $file_diff[$i]; + } + $return = ADD_BEFORE; + } + + // Recheck if we got a workable find or only a empty row. + // Set to 0x00 and it will get remove later. + if (empty($find[0])) + { + $find[0] = chr(0); + } + + return($return); + } + + /** + * gen_inline_find + * Generate inline finds + * @param $del, the original string + * @param $add, the string with the new stuff + * @param $changes, the to put the changes in. There can be more than one in-line change per line + * @return $cnt, int, the number of edits in this line. + */ + private function gen_inline_find($del, $add, &$changes) + { + // str_split messes up the non English chars. + $add_arr = $this->split_string($add); + $del_arr = $this->split_string($del); + + // Let's run a diff and see what we get. + $row_diff = $this->line_diff($del_arr, $add_arr); + unset($del_arr, $add_arr); + + $cnt = 0; + + // Need to remember the last find so we don't try to reuse it. + $last_find = -1; + + // We need to keep track of the last post in the array. We can't use isset() for this. + $end = sizeof($row_diff); + + foreach ($row_diff as $key => &$value) + { + if (is_array($value)) + { + if (empty($value['del']) && empty($value['add'])) + { + // Nothing to add or remove. + unset($value); + continue; + } + + // Is this a replace or a add? + else if (!empty($value['add']) && empty($value['del'])) + { + // This is a add + // We want at least 6 chars for the inline find. + $changes[$cnt]['inline-find'] = ''; + if ($key <= 2) + { + // The change is in the beginning of the line. + $i = ($key + 1 > $last_find) ? $key + 1 : $last_find + 1; + while ($i < $end && !@is_array($row_diff[$i])) + { + // $row_diff[$i] might have been removed. + $changes[$cnt]['inline-find'] .= (isset($row_diff[$i])) ? $row_diff[$i] : ''; + $i++; + } + $last_find = $i - 1; + $changes[$cnt]['add-type'] = ADD_BEFORE; + } + else + { + $i = $key - 1; + while ($i >= 0 && !@is_array($row_diff[$i])) + { + // We have enough finds to do a add after. + $changes[$cnt]['inline-find'] = (isset($row_diff[$i]) && $i > $last_find) ? $row_diff[$i] . $changes[$cnt]['inline-find'] : $changes[$cnt]['inline-find']; + $i--; + } + $last_find = $key - 1; + // The string comes in backwards so we need to turn it right. + $changes[$cnt]['add-type'] = ADD_AFTER; + } + $changes[$cnt]['add'] = ''; + foreach ($value['add'] as $char) + { + // What to add before or after + $changes[$cnt]['add'] .= $char; + } + $cnt++; + } + else if (!empty($value['add']) && !empty($value['del'])) + { + // This is a replace + $inline_find = ''; + foreach ($value['del'] as $char) + { + $inline_find .= $char; + } + $inline_add = ''; + foreach ($value['add'] as $char) + { + $inline_add .= $char; + } + + $changes[$cnt]['inline-find'] = $inline_find; + $changes[$cnt]['add'] = $inline_add; + $changes[$cnt]['add-type'] = REPLACE; + $cnt++; + } + else if (empty($value['add']) && !empty($value['del'])) + { + // This is a delete + $inline_find = ''; + foreach ($value['del'] as $char) + { + $inline_find .= $char; + } + + $changes[$cnt]['inline-find'] = ''; + foreach ($value['del'] as $char) + { + $changes[$cnt]['inline-find'] .= $char; + } + $changes[$cnt]['add'] = ''; + $changes[$cnt]['add-type'] = REPLACE; + $cnt++; + } + // Unset empty finds so mark_finds get a easier job. + // Can't use empty() here because that removes strings containing only a zero. + if (isset($changes[$cnt - 1]['inline-find']) && $changes[$cnt - 1]['inline-find'] == '') + { + unset($changes[$cnt-1]['inline-find']); + } + } + } + unset($key, $value,$char); + + // Before returning, let's get sure the right in-line edits are closed. + $changes = $this->mark_finds($changes, true); + + return($cnt); + } + +/** + * Saved this for now so we can go back to char diff if we want + private function gen_inline_find($del, $add, &$changes) + { + // str_split messes up the non English chars. + $add_arr = $this->split_string($add); + $del_arr = $this->split_string($del); + + // Let's run a diff and see what we get. + $row_diff = $this->line_diff($del_arr, $add_arr); + unset($del_arr, $add_arr); + + $cnt = 0; + + // Need to remember the last find so we don't try to reuse it. + $last_find = -1; + + // We need to keep track of the last post in the array. We can't use isset() for this. + $end = sizeof($row_diff); + + foreach ($row_diff as $key => &$value) + { + if (is_array($value)) + { + if (empty($value['del']) && empty($value['add'])) + { + // Nothing to add or remove. + unset($value); + continue; + } + + // Is this a replace or a add? + else if (!empty($value['add']) && empty($value['del'])) + { + // This is a add + // We want at least 6 chars for the inline find. + $changes[$cnt]['inline-find'] = ''; + if ($key <= 6) + { + // The change is in the beginning of the line. + $i = ($key + 1 > $last_find) ? $key + 1 : $last_find + 1; + while ($i < $end && !@is_array($row_diff[$i])) + { + // $row_diff[$i] might have been removed. + $changes[$cnt]['inline-find'] .= (isset($row_diff[$i])) ? $row_diff[$i] : ''; + $i++; + } + $last_find = $i - 1; + $changes[$cnt]['add-type'] = ADD_BEFORE; + } + else + { + $i = $key - 1; + while ($i >= 0 && !@is_array($row_diff[$i])) + { + // We have enough finds to do a add after. + $changes[$cnt]['inline-find'] = (isset($row_diff[$i]) && $i > $last_find) ? $row_diff[$i] . $changes[$cnt]['inline-find'] : $changes[$cnt]['inline-find']; + $i--; + } + $last_find = $key - 1; + // The string comes in backwards so we need to turn it right. + $changes[$cnt]['add-type'] = ADD_AFTER; + } + $changes[$cnt]['add'] = ''; + foreach ($value['add'] as $char) + { + // What to add before or after + $changes[$cnt]['add'] .= $char; + } + $cnt++; + } + else if (!empty($value['add']) && !empty($value['del'])) + { + // This is a replace + $inline_find = ''; + foreach ($value['del'] as $char) + { + $inline_find .= $char; + } + $inline_add = ''; + foreach ($value['add'] as $char) + { + $inline_add .= $char; + } + + $changes[$cnt]['inline-find'] = $inline_find; + $changes[$cnt]['add'] = $inline_add; + $changes[$cnt]['add-type'] = REPLACE; + $cnt++; + } + else if (empty($value['add']) && !empty($value['del'])) + { + // This is a delete + $inline_find = ''; + foreach ($value['del'] as $char) + { + $inline_find .= $char; + } + + $changes[$cnt]['inline-find'] = ''; + foreach ($value['del'] as $char) + { + $changes[$cnt]['inline-find'] .= $char; + } + $changes[$cnt]['add'] = ''; + $changes[$cnt]['add-type'] = REPLACE; + $cnt++; + } + // Unset empty finds so mark_finds get a easier job. + // Can't use empty() here because that removes strings containing only a zero. + if (isset($changes[$cnt - 1]['inline-find']) && $changes[$cnt - 1]['inline-find'] == '') + { + unset($changes[$cnt-1]['inline-find']); + } + } + } + unset($key, $value,$char); + + // Before returning, let's get sure the right in-line edits are closed. + $changes = $this->mark_finds($changes, true); + + return($cnt); + } +**/ + + /** + * split_string + * splits a string to a array. str_split messes up multibyte chars. + * @param $str, string to split + * @return $arr, the array + */ + private function split_string($str) + { + $arr = array(); + + $in_word = false; + $cnt = -1; + + for ($i = 0, $end = strlen($str); $i < $end; $i++) + { + $char = substr($str, $i, 1); + if (in_array($char, $this->separator)) + { + // This is a separator char. + $cnt++; + $in_word = false; + $arr[$cnt] = $char; + } + else + { + // Here we build words. + if ($in_word) + { + $arr[$cnt] .= $char; + } + else + { + $cnt++; + $in_word = true; + $arr[$cnt] = $char; + } + } + } + +/** + * Saved for the char diff. + for ($i = 0, $end = strlen($str); $i < $end; $i++) + { + $arr[] = substr($str, $i, 1); + } +**/ + + return($arr); + } + + /** + * Generate the inline diffs. + * From http://compsci.ca/v3/viewtopic.php?p=142539 slightly modified. + * @param $old, the original array + * @param $new, the modified array + * @return array with the diff + */ + function line_diff($old, $new) + { + $maxlen = 0; + foreach ($old as $oindex => $ovalue) + { + $nkeys = array_keys($new, $ovalue); + foreach ($nkeys as $nindex) + { + $matrix[$oindex][$nindex] = isset($matrix[$oindex - 1][$nindex - 1]) ? $matrix[$oindex - 1][$nindex - 1] + 1 : 1; + if ($matrix[$oindex][$nindex] > $maxlen) + { + $maxlen = $matrix[$oindex][$nindex]; + $omax = $oindex + 1 - $maxlen; + $nmax = $nindex + 1 - $maxlen; + } + } + } + if ($maxlen == 0) + { + return array(array('del'=>$old, 'add'=>$new)); + } + + return array_merge($this->line_diff(array_slice($old, 0, $omax), array_slice($new, 0, $nmax)), + array_slice($new, $nmax, $maxlen), + $this->line_diff(array_slice($old, $omax + $maxlen), array_slice($new, $nmax + $maxlen))); + } + + /** + * mark_finds + * Check if the next edit has a find or not. + * This is needed to know if the edit tag should be closed or not. + * Steps backwards trough the array and sets 'close' if the next change has a find in it. + * If not, the edit tag should not be closed. + * + * @param $diff_arr, The well known diff + * @return $diff_arr. The same array with the + */ + private function mark_finds($diff_arr, $inline = false) + { + // The last change always needs ot have close on. + $close = true; + // Step backwards trough the array + $find = ($inline) ? 'inline-find' : 'find'; + for ($i = sizeof($diff_arr) - 1; $i > -1; $i--) + { + if (is_array($diff_arr[$i])) + { + if ($close) + { + $diff_arr[$i]['close'] = true; + } + // Now to check if this edit has any finds or not. + if (isset($diff_arr[$i][$find])) + { + // This element has a find so the previous change should close its edit. + $close = true; + } + else + { + // This element has not a find so the previous change should leave the edit open. + $close = false; + } + } + } + return($diff_arr); + } + +} +?> \ No newline at end of file