2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
42 * This is a utility base file to parse HTML
52 function MetaParser() {
57 return "NOT AVAILABLE";
62 * Parses for contents enclosed within <form>...</form> tags
64 function getFormContents($contents, $all = true) {
66 preg_match_all("'(<form[^>]*?>)(.*?)(</form[^>]*?>)'si", $contents, $matches);
70 preg_match("'(<form[^>]*?>)(.*?)(</form[^>]*?>)'si", $contents, $matches);
71 return $this->convertToTagElement($matches);
78 * Parses for input, select, textarea types from string content
79 * @param $contents The String contents to parse
80 * @return $matches Array of matches of PREG_SET_ORDER
82 function getFormElements($contents) {
83 preg_match_all("'(<[ ]*?)(textarea|input|select)([^>]*?)(>)'si", $contents, $matches, PREG_PATTERN_ORDER);
85 foreach($matches[3] as $match) {
93 * getFormElementsNames
94 * Parses for the name values of input, select, textarea types from string content
95 * @param $contents The String contents to parse
96 * @return $matches Array of name/value pairs
98 function getFormElementsNames($contents) {
99 preg_match_all("'(<[ ]*?)(textarea|input|select)[^>]*?name=[\'\"]([^\'\"]*?)(\[\])?(_basic)?[\'\"]([^>]*?>)'si", $contents, $matches, PREG_PATTERN_ORDER);
100 return !empty($matches[3]) ? $matches[3] : null;
106 * Returns the name/value of a tag attribute where name is set to $name
107 * @param $name The name of the attribute
108 * @param $contents The contents to parse
109 * @param $filter Option regular expression to filter value
110 * @return Array of name/value for matching attribute
112 function getTagAttribute($name, $contents, $filter = '') {
113 //$exp = "'".$name."[ ]*?=[ ]*?[\'\"]([a-zA-Z0-9\_\[\]]*)[\'\"]'si";
115 $exp = "'".$name."[\s]*?=[\s]*?[\'\"]([^\'^\"]*?)[\'\"]'si";
116 preg_match_all($exp, $contents, $matches, PREG_SET_ORDER);
118 return !empty($matches[0][1]) ? $matches[0][1] : '';
122 foreach($matches as $tag) {
123 if(preg_match($filter, $tag[1])) {
132 * Returns an Array of the tables found in the file. If $tableClass parameter
133 * is supplied, it'll return only those tables that have a matching class attribute
134 * equal to $tableClass
135 * @param $tableClass Optional table class parameter value
136 * @return Array of table elements found
138 function getTables($tableClass = null, $contents) {
139 preg_match_all("'(<table[^>]*?>)(.*?)(</table[^>]*?>)'si", $contents, $matches, PREG_SET_ORDER);
140 if($tableClass == null) {
145 foreach($matches as $key => $table) {
146 if(strpos($table[1], $tableClass) > 0) {
150 return $this->convertToTagElement($tables);
156 * Returns an Array of all elements matching type. It will match
157 * for the outermost tags. For example given contents:
158 * "<tr><td>Text <table><tr><td>a</td></tr></table></td></tr>"
159 * and method call getElementsByType("<td>", $contents) returns
160 * "<td>Text <table><tr><td>a</td></tr></table></td>"
162 * @param $type The type of element to parse out and return
163 * @return a tag element format Array
165 function getElementsByType($type, $contents) {
166 $x = strlen($contents);
169 $stag1 = "<" . trim($type, " <>") . '>';
170 $stag2 = "<" . trim($type, " <>") . ' ';
171 $etag = "</".$type.">";
172 $sincrement = strlen($stag1);
173 $eincrement = strlen($etag);
178 $stok = substr($contents, $count, $sincrement);
179 $etok = substr($contents, $count, $eincrement);
180 if($stok == $stag1 || $stok == $stag2) {
182 if(count($sarr) == 0) {
187 } else if($etok == $etag) {
189 if(count($sarr) == 0) {
190 $val = substr($contents, $mark, ($count - $mark) + $eincrement);
208 function getElementValue($type, $contents, $filter = "(.*?)") {
209 $exp = "'<".$type."[^>]*?>".$filter."</".$type."[^>]*?>'si";
210 preg_match($exp, $contents, $matches);
211 return isset($matches[1]) ? $matches[1] : '';
215 function stripComments($contents) {
216 return preg_replace("'(<!--.*?-->)'si", "", $contents);
221 * This method accepts the file contents and uses the $GLOBALS['sugar_flavor'] value
222 * to remove the flavor tags in the file contents if present. If $GLOBALS['sugar_flavor']
223 * is not set, it defaults to PRO flavor
224 * @param $contents The file contents as a String value
225 * @param $result The file contents with non-matching flavor tags and their nested comments removed
227 function stripFlavorTags($contents) {
228 $flavor = isset($GLOBALS['sugar_flavor']) ? $GLOBALS['sugar_flavor'] : 'PRO';
229 $isPro = ($flavor == 'ENT' || $flavor == 'PRO') ? true : false;
231 $contents = preg_replace('/<!-- BEGIN: open_source -->.*?<!-- END: open_source -->/', '', $contents);
233 $contents = preg_replace('/<!-- BEGIN: pro -->.*?<!-- END: pro -->/', '', $contents);
240 * Returns the highest number of <td>...</td> blocks within a <tr>...</tr> block.
241 * @param $contents The table contents to parse
242 * @param $filter Optional filter to parse for an attribute within the td block.
243 * @return The maximum column count
245 function getMaxColumns($contents, $filter) {
246 preg_match_all("'(<tr[^>]*?>)(.*?)(</tr[^>]*?>)'si", $contents, $matches, PREG_SET_ORDER);
248 foreach($matches as $tableRows) {
249 $count = substr_count($tableRows[2], $filter);
258 function convertToTagElement($matches) {
262 foreach($matches as $data) {
263 // We need 4 because the 1,2,3 indexes make up start,body,end
264 if(count($data) == 4) {
266 $element['start'] = $data[1];
267 $element['body'] = $data[2];
268 $element['end'] = $data[3];
269 $elements[] = $element;
273 return empty($elements) ? $matches : $elements;
278 * This function removes the \r (return), \n (newline) and \t (tab) markup from string
280 function trimHTML($contents) {
281 $contents = str_replace(array("\r"), array(""), $contents);
282 $contents = str_replace(array("\n"), array(""), $contents);
283 $contents = str_replace(array("\t"), array(""), $contents);
291 * This method parses the given $contents String and grabs all <script...>...</script> blocks.
292 * The method also converts values enclosed within "{...}" blocks that may need to be converted
295 * @param $contents The HTML String contents to parse
297 * @return $javascript The formatted script blocks or null if none found
299 function getJavascript($contents, $addLiterals = true) {
303 //Check if there are Javascript blocks of code to process
304 preg_match_all("'(<script[^>]*?>)(.*?)(</script[^>]*?>)'si", $contents, $matches, PREG_PATTERN_ORDER);
305 if(empty($matches)) {
309 foreach($matches[0] as $scriptBlock) {
310 $javascript .= "\n" . $scriptBlock;
313 $javascript = substr($javascript, 1);
316 //1) Calendar.setup {..} blocks
317 $javascript = preg_replace('/Calendar.setup[\s]*[\(][^\)]*?[\)][\s]*;/si', '', $javascript);
319 //Find all blocks that may need to be replaced with Smarty syntax
320 preg_match_all("'([\{])([a-zA-Z0-9_]*?)([\}])'si", $javascript, $matches, PREG_PATTERN_ORDER);
321 if(!empty($matches)) {
324 foreach($matches[0] as $xTemplateCode) {
325 if(!isset($replace[$xTemplateCode])) {
326 $replace[$xTemplateCode] = str_replace("{", "{\$", $xTemplateCode);
330 $javascript = str_replace(array_keys($replace), array_values($replace), $javascript);
337 return $this->parseDelimiters($javascript);
341 function parseDelimiters($javascript) {
343 $scriptLength = strlen($javascript);
345 $inSmartyVariable = false;
347 while($count < $scriptLength) {
349 if($inSmartyVariable) {
352 while(isset($javascript[$count]) && $javascript[$count] != '}') {
357 $newJavascript .= substr($javascript, $start, $numOfChars);
358 $inSmartyVariable = false;
362 $char = $javascript[$count];
363 $nextChar = ($count + 1 >= $scriptLength) ? '' : $javascript[$count + 1];
365 if($char == "{" && $nextChar == "$") {
366 $inSmartyVariable = true;
367 $newJavascript .= $javascript[$count];
368 } else if($char == "{") {
369 $newJavascript .= " {ldelim} ";
370 } else if($char == "}") {
371 $newJavascript .= " {rdelim} ";
373 $newJavascript .= $javascript[$count];
379 return $newJavascript;
383 * findAssignedVariableName
384 * This method provides additional support in attempting to parse the module's corresponding
385 * PHP file for either the EditView or DetailView. In the event that the subclasses cannot
386 * find a matching vardefs.php entry in the HTML file, this method can be called to parse the
387 * PHP file to see if the assignment was made using the bean's variable. If so, we return
388 * this variable name.
390 * @param $name The tag name found in the HTML file for which we want to search
391 * @param $filePath The full file path for the HTML file
392 * @return The variable name found in PHP file, original $name variable if not found
394 function findAssignedVariableName($name, $filePath) {
396 if($this->mPHPFile == "INVALID") {
400 if(!isset($this->mPHPFile)) {
401 if(preg_match('/(.*?)(DetailView).html$/', $filePath, $matches)) {
403 } else if(preg_match('/(.*?)(EditView).html$/', $filePath, $matches)) {
407 if(!isset($dir) || !is_dir($dir)) {
408 $this->mPHPFile = "INVALID";
412 $filesInDir = $this->dirList($dir);
413 $phpFile = $matches[2].'.*?[\.]php';
414 foreach($filesInDir as $file) {
415 if(preg_match("/$phpFile/", $file)) {
416 $this->mPHPFile = $matches[1] . $file;
421 if(!isset($this->mPHPFile) || !file_exists($this->mPHPFile)) {
422 $this->mPHPFile = "INVALID";
427 $phpContents = file_get_contents($this->mPHPFile);
428 $uname = strtoupper($name);
429 if(preg_match("/xtpl->assign[\(][\"\']".$uname."[\"\'][\s]*?,[\s]*?[\$]focus->(.*?)[\)]/si", $phpContents, $matches)) {
438 * Utility method to list all the files in a given directory.
440 * @param $directory The directory to scan
441 * @return $results The files in the directory that were found
443 function dirList ($directory) {
445 // create an array to hold directory list
448 // create a handler for the directory
449 $handler = opendir($directory);
451 // keep going until all files in directory have been read
452 while ($file = readdir($handler)) {
453 // if $file isn't this directory or its parent,
454 // add it to the results array
455 if ($file != '.' && $file != '..')
459 // tidy up: close the handler
467 * This method checks the mixed variable $elementNames to see if it is a custom field. A custom
468 * field is simply defined as a field that ends with "_c". If $elementNames is an Array
469 * any matching custom field value will result in a true evaluation
470 * @param $elementNames Array or String value of form element name(s).
471 * @return String name of custom field; null if none found
473 function getCustomField($elementNames) {
475 if(!isset($elementNames) || (!is_string($elementNames) && !is_array($elementNames))) {
479 if(is_string($elementNames)) {
480 if(preg_match('/(.+_c)(_basic)?(\[\])?$/', $elementNames, $matches)) {
481 return count($matches) == 1 ? $matches[0] : $matches[1];
486 foreach($elementNames as $name) {
487 if(preg_match('/(.+_c)(_basic)?(\[\])?$/', $name, $matches)) {
488 return count($matches) == 1 ? $matches[0] : $matches[1];
495 function applyPreRules($moduleDir, $panels) {
496 if(file_exists("include/SugarFields/Parsers/Rules/".$moduleDir."ParseRule.php")) {
497 require_once("include/SugarFields/Parsers/Rules/".$moduleDir."ParseRule.php");
498 $class = $moduleDir."ParseRule";
499 $parseRule = new $class();
500 $panels = $parseRule->preParse($panels, $this->mView);
505 function applyRules($moduleDir, $panels) {
506 return $this->applyPostRules($moduleDir, $panels);
509 function applyPostRules($moduleDir, $panels) {
510 //Run module specific rules
511 if(file_exists("include/SugarFields/Parsers/Rules/".$moduleDir."ParseRule.php")) {
512 require_once("include/SugarFields/Parsers/Rules/".$moduleDir."ParseRule.php");
513 $class = $moduleDir."ParseRule";
514 $parseRule = new $class();
515 $panels = $parseRule->parsePanels($panels, $this->mView);
518 //Now run defined rules
519 require_once("include/SugarFields/Parsers/Rules/ParseRules.php");
520 $rules = ParseRules::getRules();
522 foreach($rules as $rule) {
523 if(!file_exists($rule['file'])) {
524 $GLOBALS['log']->error("Cannot run rule for " . $rule['file']);
527 require_once($rule['file']);
528 $runRule = new $rule['class'];
529 $panels = $runRule->parsePanels($panels, $this->mView);
536 function createFileContents($moduleDir, $panels, $templateMeta=array(), $htmlFilePath) {
538 $header = "<?php\n\n";
540 if(empty($templateMeta)) {
541 $header .= "\$viewdefs['$moduleDir']['$this->mView'] = array(
542 'templateMeta' => array('maxColumns' => '2',
544 array('label' => '10', 'field' => '30'),
545 array('label' => '10', 'field' => '30')
549 $header .= "\$viewdefs['$moduleDir']['$this->mView'] = array(
550 'templateMeta' =>" . var_export($templateMeta, true) . ",";
553 //Replace all the @sq (single quote tags that may have been inserted)
554 $header = preg_replace('/\@sq/', "'", $header);
557 $contents = file_get_contents($htmlFilePath);
559 $javascript = $this->getJavascript($contents, true);
561 if(!empty($javascript)) {
562 $javascript = str_replace("'", "\\'", $javascript);
563 $header .= "\n 'javascript' => '" . $javascript . "',\n";
566 $header .= "\n 'panels' =>";
574 $body = var_export($panels, true);
575 $metadata = $header . $body . $footer;
576 $metadata = preg_replace('/(\d+)[\s]=>[\s]?/',"",$metadata);
584 * This function merges the $panels Array against the $masterCopy's meta data definition
585 * @param $panels meta data Array to merge
586 * @param $moduleDir Directory name of the module
587 * @param $masterCopy file path to the meta data master copy
588 * @return Array of merged $panel definition
590 function mergePanels($panels, $vardefs, $moduleDir, $masterCopy) {
591 require($masterCopy);
592 $masterpanels = $viewdefs[$moduleDir][$this->mView]['panels'];
593 $hasMultiplePanels = $this->hasMultiplePanels($masterpanels);
595 if(!$hasMultiplePanels) {
596 $keys = array_keys($viewdefs[$moduleDir][$this->mView]['panels']);
597 if(!empty($keys) && count($keys) == 1) {
598 if(strtolower($keys[0]) == 'default') {
599 $masterpanels = array('default'=>$viewdefs[$moduleDir][$this->mView]['panels'][$keys[0]]);
601 $firstPanel = array_values($viewdefs[$moduleDir][$this->mView]['panels']);
602 $masterpanels = array('default'=> $firstPanel[0]);
605 $masterpanels = array('default'=>$viewdefs[$moduleDir][$this->mView]['panels']);
608 foreach($masterpanels as $name=>$masterpanel) {
609 if(isset($panels[$name])) {
610 // Get all the names in the panel
611 $existingElements = array();
612 $existingLocation = array();
614 foreach($panels[$name] as $rowKey=>$row) {
615 foreach($row as $colKey=>$column) {
616 if(is_array($column) && !empty($column['name'])) {
617 $existingElements[$column['name']] = $column['name'];
618 $existingLocation[$column['name']] = array("panel"=>$name, "row"=>$rowKey, "col"=>$colKey);
619 } else if(!is_array($column) && !empty($column)) {
620 $existingElements[$column] = $column;
621 $existingLocation[$column] = array("panel"=>$name, "row"=>$rowKey, "col"=>$colKey);
626 // Now check against the $masterCopy
627 foreach($masterpanel as $rowKey=>$row) {
631 foreach($row as $colKey=>$column) {
632 if(is_array($column) && isset($column['name'])) {
633 $id = $column['name'];
634 } else if(!is_array($column) && !empty($column)) {
639 if(empty($existingElements[$id])) {
641 // 1) if it is a required field (as defined in metadata)
642 // 2) or if it has a customLabel and customCode (a very deep customization)
643 if((is_array($column) && !empty($column['displayParams']['required'])) ||
644 (is_array($column) && !empty($column['customCode']) && !empty($column['customLabel']))) {
648 //Use definition from master copy instead
649 $panels[$existingLocation[$id]['panel']][$existingLocation[$id]['row']][$existingLocation[$id]['col']] = $column;
653 // Add it to the $panels
654 if(!empty($addRow)) {
655 $panels[$name][] = $addRow;
660 $panels[$name] = $masterpanel;
664 // We're not done yet... go through the $panels Array now and try to remove duplicate
666 foreach($panels as $name=>$panel) {
667 if(count($panel) == 0 || !isset($masterpanels[$name])) {
668 unset($panels[$name]);
677 * This function merges the $templateMeta Array against the $masterCopy's meta data definition
678 * @param $templateMeta meta data Array to merge
679 * @param $moduleDir Directory name of the module
680 * @param $masterCopy file path to the meta data master copy
681 * @return Array of merged $templateMeta definition
683 function mergeTemplateMeta($templateMeta, $moduleDir, $masterCopy) {
684 require($masterCopy);
685 $masterTemplateMeta = $viewdefs[$moduleDir][$this->mView]['templateMeta'];
687 if(isset($masterTemplateMeta['javascript'])) {
688 //Insert the getJSPath code back into src value
689 $masterTemplateMeta['javascript'] = preg_replace('/src\s*=\s*[\'\"].*?(modules\/|include\/)([^\.]*?\.js)([^\'\"]*?)[\'\"]/i', 'src="@sq . getJSPath(@sq${1}${2}@sq) . @sq"', $masterTemplateMeta['javascript']);
692 return $masterTemplateMeta;
695 function hasRequiredSpanLabel($html) {
700 return preg_match('/\<(div|span) class=(\")?required(\")?\s?>\*<\/(div|span)>/si', $html);
703 function hasMultiplePanels($panels) {
705 if(!isset($panels) || empty($panels) || !is_array($panels)) {
709 if(is_array($panels) && (count($panels) == 0 || count($panels) == 1)) {
713 foreach($panels as $panel) {
714 if(!empty($panel) && !is_array($panel)) {
717 foreach($panel as $row) {
718 if(!empty($row) && !is_array($row)) {
728 function getRelateFieldName($mixed='') {
729 if(!is_array($mixed)) {
731 } else if(count($mixed) == 2){
734 foreach($mixed as $el) {
735 if(preg_match('/_id$/', $el)) {
737 } else if(preg_match('/_name$/', $el)) {
741 return (!empty($id) && !empty($name)) ? $name : '';
746 function getCustomPanels() {
747 return $this->mCustomPanels;
751 * fixTablesWithMissingTr
752 * This is a very crude function to fix instances where files declared a table as
753 * <table...><td> instead of <table...><tr><td>. Without this helper function, the
754 * parsing could messed up.
757 function fixTablesWithMissingTr($tableContents) {
758 if(preg_match('/(<table[^>]*?[\/]?>\s*?<td)/i', $tableContents, $matches)) {
759 return preg_replace('/(<table[^>]*?[\/]?>\s*?<td)/i', '<table><tr><td', $tableContents);
761 return $tableContents;
765 * fixRowsWithMissingTr
766 * This is a very crude function to fix instances where files have an </tr> tag immediately followed by a <td> tag
768 function fixRowsWithMissingTr($tableContents) {
769 if(preg_match('/(<\/tr[^>]*?[\/]?>\s*?<td)/i', $tableContents, $matches)) {
770 return preg_replace('/(<\/tr[^>]*?[\/]?>\s*?<td)/i', '</tr><tr><td', $tableContents);
772 return $tableContents;
777 * This is a very crude function to fix instances where files have two consecutive <tr> tags
779 function fixDuplicateTrTags($tableContents) {
780 if(preg_match('/(<tr[^>]*?[\/]?>\s*?<tr)/i', $tableContents, $matches)) {
781 return preg_replace('/(<tr[^>]*?[\/]?>\s*?<tr)/i', '<tr', $tableContents);
783 return $tableContents;
787 * findSingleVardefElement
788 * Scans array of form elements to see if just one is a vardef element and, if so,
789 * return that vardef name
791 function findSingleVardefElement($formElements=array(), $vardefs=array()) {
792 if(empty($formElements) || !is_array($formElements)) {
797 foreach($formElements as $el) {
798 if(isset($vardefs[$el])) {
803 return count($found) == 1 ? $found[0] : '';