function set_array($array, $indent = 0) { $slot_start = '<slot>'; $slot_end = '</slot>'; if (empty($this->contents)) { $this->contents = 'Array(<br>'; } else { $slot_start = ''; $slot_end = ''; $this->contents .= ' Array(<br>'; } foreach ($array as $key => $arr) { for ($i = 0; $i < $indent; $i++) { $this->contents .= ' '; } $this->contents .= ' ' . $slot_start . var_export_helper($key) . $slot_end . ' => '; if (is_array($arr)) { $this->contents .= $slot_start; $this->set_array($arr, $indent + 1); $this->contents .= $slot_end; } else { $this->contents .= $slot_start . var_export_helper($arr, true) . $slot_end . '<br>'; } } for ($i = 0; $i < $indent; $i++) { $this->contents .= ' '; } $this->contents .= ');<br>'; }
/** * parse * @param $mixed * @return $obj A MetaDataBean instance **/ function parse($filePath, $vardefs = array(), $moduleDir = '', $merge = false, $masterCopy = null) { $contents = file_get_contents($filePath); $contents = $this->trimHTML($contents); // Get the second table in the page and onward $tables = $this->getElementsByType("table", $contents); //basic search table $basicSection = $this->processSection("basic", $tables[0], $filePath, $vardefs); $advancedSection = $this->processSection("advanced", $tables[1], $filePath, $vardefs); if (file_exists($masterCopy)) { require $masterCopy; $layouts = $searchdefs[$moduleDir]['layout']; if (isset($layouts['basic_search'])) { $basicSection = $this->mergeSection($basicSection, $layouts['basic_search']); $basicSection = $this->applyRules($moduleDir, $basicSection); } if (isset($layouts['advanced_search'])) { $advancedSection = $this->mergeSection($advancedSection, $layouts['advanced_search']); $advancedSection = $this->applyRules($moduleDir, $advancedSection); } } //if $header = "<?php\n\n"; $header .= "\$searchdefs['{$moduleDir}'] = array(\n 'templateMeta' => array('maxColumns' => '3', 'widths' => array('label' => '10', 'field' => '30')),\n 'layout' => array( \t\t\t\t\t\n\n\t'basic_search' =>"; $header .= "\t" . var_export_helper($basicSection); $header .= "\n\t,'advanced_search' =>"; $header .= "\t" . var_export_helper($advancedSection); $header .= "\n ),\n\n);\n?>"; $header = preg_replace('/(\\d+)[\\s]=>[\\s]?/', "", $header); return $header; }
/** * Searches through the installed relationships to find broken self referencing one-to-many relationships * (wrong field used in the subpanel, and the left link not marked as left) */ function upgrade_custom_relationships($modules = array()) { global $current_user, $moduleList; if (!is_admin($current_user)) { sugar_die($GLOBALS['app_strings']['ERR_NOT_ADMIN']); } require_once "modules/ModuleBuilder/parsers/relationships/DeployedRelationships.php"; require_once "modules/ModuleBuilder/parsers/relationships/OneToManyRelationship.php"; if (empty($modules)) { $modules = $moduleList; } foreach ($modules as $module) { $depRels = new DeployedRelationships($module); $relList = $depRels->getRelationshipList(); foreach ($relList as $relName) { $relObject = $depRels->get($relName); $def = $relObject->getDefinition(); //We only need to fix self referencing one to many relationships if ($def['lhs_module'] == $def['rhs_module'] && $def['is_custom'] && $def['relationship_type'] == "one-to-many") { $layout_defs = array(); if (!is_dir("custom/Extension/modules/{$module}/Ext/Layoutdefs") || !is_dir("custom/Extension/modules/{$module}/Ext/Vardefs")) { continue; } //Find the extension file containing the vardefs for this relationship foreach (scandir("custom/Extension/modules/{$module}/Ext/Vardefs") as $file) { if (substr($file, 0, 1) != "." && strtolower(substr($file, -4)) == ".php") { $dictionary = array($module => array("fields" => array())); $filePath = "custom/Extension/modules/{$module}/Ext/Vardefs/{$file}"; include $filePath; if (isset($dictionary[$module]["fields"][$relName])) { $rhsDef = $dictionary[$module]["fields"][$relName]; //Update the vardef for the left side link field if (!isset($rhsDef['side']) || $rhsDef['side'] != 'left') { $rhsDef['side'] = 'left'; $fileContents = file_get_contents($filePath); $out = preg_replace('/\\$dictionary[\\w"\'\\[\\]]*?' . $relName . '["\'\\[\\]]*?\\s*?=\\s*?array\\s*?\\(.*?\\);/s', '$dictionary["' . $module . '"]["fields"]["' . $relName . '"]=' . var_export_helper($rhsDef) . ";", $fileContents); file_put_contents($filePath, $out); } } } } //Find the extension file containing the subpanel definition for this relationship foreach (scandir("custom/Extension/modules/{$module}/Ext/Layoutdefs") as $file) { if (substr($file, 0, 1) != "." && strtolower(substr($file, -4)) == ".php") { $layout_defs = array($module => array("subpanel_setup" => array())); $filePath = "custom/Extension/modules/{$module}/Ext/Layoutdefs/{$file}"; include $filePath; foreach ($layout_defs[$module]["subpanel_setup"] as $key => $subDef) { if ($layout_defs[$module]["subpanel_setup"][$key]['get_subpanel_data'] == $relName) { $fileContents = file_get_contents($filePath); $out = preg_replace('/[\'"]get_subpanel_data[\'"]\\s*=>\\s*[\'"]' . $relName . '[\'"],/s', "'get_subpanel_data' => '{$def["join_key_lhs"]}',", $fileContents); file_put_contents($filePath, $out); } } } } } } } }
public function testvar_export_helper() { //execute the method and test if it returns expected values $tempArray = array('Key1' => 'value1', 'Key2' => 'value2'); $expected = "array (\n 'Key1' => 'value1',\n 'Key2' => 'value2',\n)"; $actual = var_export_helper($tempArray); $this->assertSame($actual, $expected); }
function override_recursive_helper($key_names, $array_name, $value) { if (empty($key_names)) { return "=" . var_export_helper($value, true) . ";"; } else { $key = array_shift($key_names); return "[" . var_export($key, true) . "]" . override_recursive_helper($key_names, $array_name, $value); } }
function write_array_to_file($the_name, $the_array, $the_file) { $the_string = "<?php\n" . '// created: ' . date('Y-m-d H:i:s') . "\n" . "\${$the_name} = " . var_export_helper($the_array) . ";\n?>\n"; if ($fh = @fopen($the_file, "w")) { fputs($fh, $the_string, strlen($the_string)); fclose($fh); return true; } else { return false; } }
public function run() { foreach (glob('custom/themes/clients/*/*/variables.less') as $customTheme) { $path = pathinfo($customTheme, PATHINFO_DIRNAME); $variables = $this->parseFile($path . '/variables.less'); // Convert to new defs $lessdefs = array('colors' => $variables['hex']); // Write new defs $write = "<?php\n" . '// created: ' . date('Y-m-d H:i:s') . "\n" . '$lessdefs = ' . var_export_helper($lessdefs) . ';'; sugar_file_put_contents($path . '/variables.php', $write); // Delete old defs $this->fileToDelete($path . '/variables.less'); } }
function write_array_to_file($the_name, $the_array, $the_file) { $the_string = "<?php\n" . '\\n if(empty(\\$GLOBALS["sugarEntry"])) die("Not A Valid Entry Point"); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ ' . "\n \${$the_name} = " . var_export_helper($the_array) . ";\n?>\n"; if ($fh = @sugar_fopen($the_file, "w")) { fputs($fh, $the_string); fclose($fh); return true; } else { return false; } }
protected function _saveToFile($filename, $defs, $useVariables = true, $forPopup = false) { if (file_exists($filename)) { unlink($filename); } mkdir_recursive(dirname($filename)); $useVariables = count($this->_variables) > 0 && $useVariables; // only makes sense to do the variable replace if we have variables to replace... // create the new metadata file contents, and write it out $out = "<?php\n"; if ($useVariables) { // write out the $<variable>=<modulename> lines foreach ($this->_variables as $key => $value) { $out .= "\${$key} = '" . $value . "';\n"; } } $viewVariable = $this->_fileVariables[$this->_view]; if ($forPopup) { $out .= "\${$viewVariable} = \n" . var_export_helper($defs); } else { $out .= "\${$viewVariable} [" . ($useVariables ? '$module_name' : "'{$this->_moduleName}'") . "] = \n" . var_export_helper($defs); } $out .= ";\n?>\n"; if (sugar_file_put_contents($filename, $out) === false) { $GLOBALS['log']->fatal(get_class($this) . ": could not write new viewdef file " . $filename); } }
function _writeToFile($file, $view, $moduleName, $defs, $variables) { if (file_exists($file)) { unlink($file); } mkdir_recursive(dirname($file)); $GLOBALS['log']->debug("ModuleBuilderParser->_writeFile(): file=" . $file); $useVariables = count($variables) > 0; if ($fh = @sugar_fopen($file, 'w')) { $out = "<?php\n"; if ($useVariables) { // write out the $<variable>=<modulename> lines foreach ($variables as $key => $value) { $out .= "\${$key} = '" . $value . "';\n"; } } // write out the defs array itself switch (strtolower($view)) { case 'editview': case 'detailview': case 'quickcreate': $defs = array($view => $defs); break; default: break; } $viewVariable = $this->_defMap[strtolower($view)]; $out .= "\${$viewVariable} = "; $out .= $useVariables ? "array (\n\$module_name =>\n" . var_export_helper($defs) : var_export_helper(array($moduleName => $defs)); // tidy up the parenthesis if ($useVariables) { $out .= "\n)"; } $out .= ";\n?>\n"; // $GLOBALS['log']->debug("parser.modifylayout.php->_writeFile(): out=".print_r($out,true)); fputs($fh, $out); fclose($fh); } else { $GLOBALS['log']->fatal("ModuleBuilderParser->_writeFile() Could not write new viewdef file " . $file); } }
/** * Does the actual authentication of the user and returns an id that will be used * to load the current user (loadUserOnSession) * * @param STRING $name * @param STRING $password * @return STRING id - used for loading the user * * Contributions by Erik Mitchell erikm@logicpd.com */ function authenticateUser($name, $password) { $server = $GLOBALS['ldap_config']->settings['ldap_hostname']; $port = $GLOBALS['ldap_config']->settings['ldap_port']; if (!$port) { $port = DEFAULT_PORT; } Log::debug("ldapauth: Connecting to LDAP server: {$server}"); $ldapconn = ldap_connect($server, $port); $error = ldap_errno($ldapconn); if ($this->loginError($error)) { return ''; } @ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); @ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0); // required for AD // If constant is defined, set the timeout (PHP >= 5.3) if (defined('LDAP_OPT_NETWORK_TIMEOUT')) { // Network timeout, lower than PHP and DB timeouts @ldap_set_option($ldapconn, LDAP_OPT_NETWORK_TIMEOUT, 60); } $bind_user = $this->ldap_rdn_lookup($name, $password); Log::debug("ldapauth.ldap_authenticate_user: ldap_rdn_lookup returned bind_user="******"SECURITY: ldapauth: failed LDAP bind (login) by " . $name . ", could not construct bind_user"); return ''; } // MRF - Bug #18578 - punctuation was being passed as HTML entities, i.e. & $bind_password = html_entity_decode($password, ENT_QUOTES); Log::info("ldapauth: Binding user " . $bind_user); $bind = ldap_bind($ldapconn, $bind_user, $bind_password); $error = ldap_errno($ldapconn); if ($this->loginError($error)) { $full_user = $GLOBALS['ldap_config']->settings['ldap_bind_attr'] . "=" . $bind_user . "," . $GLOBALS['ldap_config']->settings['ldap_base_dn']; Log::info("ldapauth: Binding user " . $full_user); $bind = ldap_bind($ldapconn, $full_user, $bind_password); $error = ldap_errno($ldapconn); if ($this->loginError($error)) { return ''; } } Log::info("ldapauth: Bind attempt complete."); if ($bind) { // Authentication succeeded, get info from LDAP directory $attrs = array_keys($GLOBALS['ldapConfig']['users']['fields']); $base_dn = $GLOBALS['ldap_config']->settings['ldap_base_dn']; $name_filter = $this->getUserNameFilter($name); //add the group user attribute that we will compare to the group attribute for membership validation if group membership is turned on if (!empty($GLOBALS['ldap_config']->settings['ldap_group']) && !empty($GLOBALS['ldap_config']->settings['ldap_group_user_attr']) && !empty($GLOBALS['ldap_config']->settings['ldap_group_attr'])) { if (!in_array($attrs, $GLOBALS['ldap_config']->settings['ldap_group_user_attr'])) { $attrs[] = $GLOBALS['ldap_config']->settings['ldap_group_user_attr']; } } Log::debug("ldapauth: Fetching user info from Directory using base dn: " . $base_dn . ", name_filter: " . $name_filter . ", attrs: " . var_export_helper($attrs)); $result = @ldap_search($ldapconn, $base_dn, $name_filter, $attrs); $error = ldap_errno($ldapconn); if ($this->loginError($error)) { return ''; } Log::debug("ldapauth: ldap_search complete."); $info = @ldap_get_entries($ldapconn, $result); $error = ldap_errno($ldapconn); if ($this->loginError($error)) { return ''; } Log::debug("ldapauth: User info from Directory fetched."); // some of these don't seem to work $this->ldapUserInfo = array(); foreach ($GLOBALS['ldapConfig']['users']['fields'] as $key => $value) { //MRF - BUG:19765 $key = strtolower($key); if (isset($info[0]) && isset($info[0][$key]) && isset($info[0][$key][0])) { $this->ldapUserInfo[$value] = $info[0][$key][0]; } } //we should check that a user is a member of a specific group if (!empty($GLOBALS['ldap_config']->settings['ldap_group'])) { Log::debug("LDAPAuth: scanning group for user membership"); $group_user_attr = $GLOBALS['ldap_config']->settings['ldap_group_user_attr']; $group_attr = $GLOBALS['ldap_config']->settings['ldap_group_attr']; if (!isset($info[0][$group_user_attr])) { Log::fatal("ldapauth: {$group_user_attr} not found for user {$name} cannot authenticate against an LDAP group"); ldap_close($ldapconn); return ''; } else { $user_uid = $info[0][$group_user_attr]; if (is_array($user_uid)) { $user_uid = $user_uid[0]; } // If user_uid contains special characters (for LDAP) we need to escape them ! $user_uid = str_replace(array("(", ")"), array("\\(", "\\)"), $user_uid); } // build search query and determine if we are searching for a bare id or the full dn path $group_name = $GLOBALS['ldap_config']->settings['ldap_group_name'] . "," . $GLOBALS['ldap_config']->settings['ldap_group_dn']; Log::debug("ldapauth: Searching for group name: " . $group_name); $user_search = ""; if (!empty($GLOBALS['ldap_config']->settings['ldap_group_attr_req_dn']) && $GLOBALS['ldap_config']->settings['ldap_group_attr_req_dn'] == 1) { Log::debug("ldapauth: Checking for group membership using full user dn"); $user_search = "({$group_attr}=" . $group_user_attr . "=" . $user_uid . "," . $base_dn . ")"; } else { $user_search = "({$group_attr}=" . $user_uid . ")"; } Log::debug("ldapauth: Searching for user: "******"ldapauth: User ({$name}) is not a member of the LDAP group"); $user_id = var_export_helper($user_uid); Log::debug("ldapauth: Group DN:{$GLOBALS['ldap_config']->settings['ldap_group_dn']}" . " Group Name: " . $GLOBALS['ldap_config']->settings['ldap_group_name'] . " Group Attribute: {$group_attr} User Attribute: {$group_user_attr} :(" . $user_uid . ")"); ldap_close($ldapconn); return ''; } } ldap_close($ldapconn); $dbresult = $GLOBALS['db']->query("SELECT id, status FROM users WHERE user_name='" . $name . "' AND deleted = 0"); //user already exists use this one if ($row = $GLOBALS['db']->fetchByAssoc($dbresult)) { if ($row['status'] != 'Inactive') { return $row['id']; } else { return ''; } } //create a new user and return the user if ($GLOBALS['ldap_config']->settings['ldap_auto_create_users']) { return $this->createUser($name); } return ''; } else { Log::fatal("SECURITY: failed LDAP bind (login) by {$this->user_name} using bind_user={$bind_user}"); Log::fatal("ldapauth: failed LDAP bind (login) by {$this->user_name} using bind_user={$bind_user}"); ldap_close($ldapconn); return ''; } }
function handleSave($populate = true) { if (empty($this->_packageName)) { foreach (array(MB_CUSTOMMETADATALOCATION, MB_BASEMETADATALOCATION) as $value) { $file = $this->implementation->getFileName(MB_POPUPLIST, $this->_moduleName, $value); if (file_exists($file)) { break; } } $writeFile = $this->implementation->getFileName(MB_POPUPLIST, $this->_moduleName); if (!file_exists($writeFile)) { mkdir_recursive(dirname($writeFile)); } } else { $writeFile = $file = $this->implementation->getFileName(MB_POPUPLIST, $this->_moduleName, $this->_packageName); } $this->implementation->_history->append($file); if ($populate) { $this->_populateFromRequest(); } $out = "<?php\n"; //Load current module languages global $mod_strings, $current_language; $oldModStrings = $mod_strings; $GLOBALS['mod_strings'] = return_module_language($current_language, $this->_moduleName); require $file; if (!isset($popupMeta)) { sugar_die("unable to load Module Popup Definition"); } if ($this->_view == MB_POPUPSEARCH) { foreach ($this->_viewdefs as $k => $v) { if (isset($this->_viewdefs[$k]) && isset($this->_viewdefs[$k]['default'])) { unset($this->_viewdefs[$k]['default']); } } $this->_viewdefs = $this->convertSearchToListDefs($this->_viewdefs); $popupMeta['searchdefs'] = $this->_viewdefs; $this->addNewSearchDef($this->_viewdefs, $popupMeta); } else { $popupMeta['listviewdefs'] = array_change_key_case($this->_viewdefs, CASE_UPPER); } //provide a way for users to add to the reserve properties list via the 'addToReserve' element $totalReserveProps = self::$reserveProperties; if (!empty($popupMeta['addToReserve'])) { $totalReserveProps = array_merge(self::$reserveProperties, $popupMeta['addToReserve']); } $allProperties = array_merge($totalReserveProps, array('searchdefs', 'listviewdefs')); $out .= "\$popupMeta = array (\n"; foreach ($allProperties as $p) { if (isset($popupMeta[$p])) { $out .= " '{$p}' => " . var_export_helper($popupMeta[$p]) . ",\n"; } } $out .= ");\n"; file_put_contents($writeFile, $out); //return back mod strings $GLOBALS['mod_strings'] = $oldModStrings; }
/** * @param string $fileNameToUpdate * @param array $app_list_strings * @param array $app_strings * @param int $keyCount - How many keys were changed * @param bool $fullArray - denotes if this is the full array or just additions */ private function writeLanguageFile($fileNameToUpdate, $app_list_strings, $app_strings, $keyCount, $fullArray) { $this->logThis("-> Updating"); $this->backupFile($fileNameToUpdate); $GLOBALS['log']->debug("fixLanguageFiles: BEGIN writeLanguageFile {$fileNameToUpdate}"); if (!is_writable($fileNameToUpdate)) { $this->logThis("{$fileNameToUpdate} is not writable!!!!!!!", self::SEV_HIGH); } if ($keyCount > 0) { $this->logThis("-> {$keyCount} keys changed"); } $flags = LOCK_EX; $moduleList = false; $moduleListSingular = false; $phpTag = "<?php"; if (count($app_list_strings) > 0) { foreach ($app_list_strings as $key => $value) { if ($key == 'moduleList' && $moduleList == false) { $the_string = "{$phpTag}\n"; foreach ($value as $mKey => $mValue) { if (!empty($mValue)) { $the_string .= "\$app_list_strings['moduleList']['{$mKey}'] = '{$mValue}';\n"; } } sugar_file_put_contents($fileNameToUpdate, $the_string, $flags); $flags = FILE_APPEND | LOCK_EX; $phpTag = ""; $moduleList = true; } elseif ($key == 'moduleListSingular' && $moduleListSingular == false) { $the_string = "{$phpTag}\n"; foreach ($value as $mKey => $mValue) { if (!empty($mValue)) { $the_string .= "\$app_list_strings['moduleListSingular']['{$mKey}'] = '{$mValue}';\n"; } } sugar_file_put_contents($fileNameToUpdate, $the_string, $flags); $flags = FILE_APPEND | LOCK_EX; $phpTag = ""; $moduleListSingular = true; } else { if ($fullArray) { $the_string = "{$phpTag}\n\$app_list_strings['{$key}'] = " . var_export_helper($app_list_strings[$key]) . ";\n"; } else { $the_string = "{$phpTag}\n"; foreach ($value as $mKey => $mValue) { if (!empty($mValue)) { $the_string .= "\$app_list_strings['moduleList']['{$mKey}'] = '{$mValue}';\n"; } } } sugar_file_put_contents($fileNameToUpdate, $the_string, $flags); $flags = FILE_APPEND | LOCK_EX; $phpTag = ""; } } } else { $flags = LOCK_EX; } if (count($app_strings) > 0) { $the_string = "{$phpTag}\n"; foreach ($app_strings as $key => $value) { if ($value == NULL || $key == NULL) { continue; } $the_string .= "\$app_strings['{$key}']='{$value}';\n"; } sugar_file_put_contents($fileNameToUpdate, $the_string, $flags); } //Make sure the final file is loadable // If there is an error this REQUIRE will error out require $fileNameToUpdate; $GLOBALS['log']->debug("fixLanguageFiles: END writeLanguageFile"); }
function setLastUser($user_id, $id) { $_SESSION['lastuser'][$id] = $user_id; $file = create_cache_directory('modules/AOW_WorkFlow/Users/') . $id . 'lastUser.cache.php'; $arrayString = var_export_helper(array('User' => $user_id)); $content = <<<eoq <?php \t\$lastUser = {$arrayString}; ?> eoq; if ($fh = @sugar_fopen($file, 'w')) { fputs($fh, $content); fclose($fh); } return true; }
/** * Performs the actual file write. Abstracted from writeCacheFile() for * flexibility * @param array $array The array to write to the cache * @param string $file Full path (relative) with cache file name * @return bool */ function _writeCacheFile($array, $file) { global $sugar_config; $arrayString = var_export_helper($array); $date = date("r"); $the_string = <<<eoq <?php // created: {$date} \t\$cacheFile = {$arrayString}; ?> eoq; if ($fh = @sugar_fopen($file, "w")) { fputs($fh, $the_string); fclose($fh); return true; } else { $GLOBALS['log']->debug("EMAILUI: Could not write cache file [ {$file} ]"); return false; } }
function handleSave($populate = true) { if (empty($this->_packageName)) { foreach (array(MB_CUSTOMMETADATALOCATION, MB_BASEMETADATALOCATION) as $value) { $file = $this->implementation->getFileName(MB_DASHLET, $this->_moduleName, $value); if (file_exists($file)) { break; } } $writeTodashletName = $dashletName = $this->implementation->getLanguage() . 'Dashlet'; if (!file_exists($file)) { $file = "modules/{$this->_moduleName}/Dashlets/My{$this->_moduleName}Dashlet/My{$this->_moduleName}Dashlet.data.php"; $dashletName = 'My' . $this->implementation->getLanguage() . 'Dashlet'; } $writeFile = $this->implementation->getFileName(MB_DASHLET, $this->_moduleName); if (!file_exists($writeFile)) { mkdir_recursive(dirname($writeFile)); } } else { $writeFile = $file = $this->implementation->getFileName(MB_DASHLET, $this->_moduleName, $this->_packageName); $writeTodashletName = $dashletName = $this->implementation->module->key_name . 'Dashlet'; } $this->implementation->_history->append($file); if ($populate) { $this->_populateFromRequest(); } $out = "<?php\n"; require $file; if (!isset($dashletData[$dashletName])) { sugar_die("unable to load Module Dashlet Definition"); } if ($fh = sugar_fopen($writeFile, 'w')) { if ($this->_view == MB_DASHLETSEARCH) { $dashletData[$dashletName]['searchFields'] = $this->ConvertSearchToDashletDefs($this->_viewdefs); } else { $dashletData[$dashletName]['columns'] = $this->_viewdefs; } $out .= "\$dashletData['{$writeTodashletName}']['searchFields'] = " . var_export_helper($dashletData[$dashletName]['searchFields']) . ";\n"; $out .= "\$dashletData['{$writeTodashletName}']['columns'] = " . var_export_helper($dashletData[$dashletName]['columns']) . ";\n"; fputs($fh, $out); fclose($fh); } }
/** * This method updates the metadata files (detailviewdefs.php) according to the settings in display_config.php * * @return bool $result boolean value indicating whether or not the method successfully completed. */ public static function updateMetaDataFiles() { if (file_exists(CONNECTOR_DISPLAY_CONFIG_FILE)) { $modules_sources = []; require CONNECTOR_DISPLAY_CONFIG_FILE; Log::debug(var_export_helper($modules_sources, true)); if (!empty($modules_sources)) { foreach ($modules_sources as $module => $mapping) { $metadata_file = file_exists("custom/modules/{$module}/metadata/detailviewdefs.php") ? "custom/modules/{$module}/metadata/detailviewdefs.php" : "modules/{$module}/metadata/detailviewdefs.php"; $viewdefs = []; if (!file_exists($metadata_file)) { Log::info("Unable to update metadata file for module: {$module}"); continue; } else { require $metadata_file; } $insertConnectorButton = true; self::removeHoverField($viewdefs, $module); //Insert the hover field if available if (!empty($mapping)) { require_once 'include/connectors/sources/SourceFactory.php'; require_once 'include/connectors/formatters/FormatterFactory.php'; $shown_formatters = []; foreach ($mapping as $id) { $source = SourceFactory::getSource($id, false); if ($source->isEnabledInHover() && $source->isRequiredConfigFieldsForButtonSet()) { $shown_formatters[$id] = FormatterFactory::getInstance($id); } } //Now we have to decide which field to put it on... use the first one for now if (!empty($shown_formatters)) { foreach ($shown_formatters as $id => $formatter) { $added_field = false; $formatter_mapping = $formatter->getSourceMapping(); $source = $formatter->getComponent()->getSource(); //go through the mapping and add the hover to every field define in the mapping //1) check for hover fields $hover_fields = $source->getFieldsWithParams('hover', true); foreach ($hover_fields as $key => $def) { if (!empty($formatter_mapping['beans'][$module][$key])) { $added_field = self::setHoverField($viewdefs, $module, $formatter_mapping['beans'][$module][$key], $id); } } //2) check for first mapping field if (!$added_field && !empty($formatter_mapping['beans'][$module])) { foreach ($formatter_mapping['beans'][$module] as $key => $val) { $added_field = self::setHoverField($viewdefs, $module, $val, $id); if ($added_field) { break; } } } } //foreach //Log an error message if (!$added_field) { Log::fatal("Unable to place hover field link on metadata for module {$module}"); } } } //Make the directory for the metadata file if (!file_exists("custom/modules/{$module}/metadata")) { mkdir_recursive("custom/modules/{$module}/metadata"); } if (!write_array_to_file('viewdefs', $viewdefs, "custom/modules/{$module}/metadata/detailviewdefs.php")) { Log::fatal("Cannot update file custom/modules/{$module}/metadata/detailviewdefs.php"); return false; } if (file_exists($cachedfile = sugar_cached("modules/{$module}/DetailView.tpl")) && !unlink($cachedfile)) { Log::fatal("Cannot delete file {$cachedfile}"); return false; } } } } return true; }
public function testUsingCustomPopUpElements() { //declare the vars global and then include the modules file to make sure they are available during testing global $moduleList, $beanList, $beanFiles; include 'include/modules.php'; if (empty($GLOBALS['app_list_strings'])) { $language = $GLOBALS['current_language']; $GLOBALS['app_list_strings'] = return_app_list_strings_language($language); } //write out to file and assert that the file was written, or we shouldn't continue $meta = "<?php\n \$popupMeta = array (\n"; foreach ($this->newPopupMeta as $k => $v) { $meta .= " '{$k}' => " . var_export_helper($v) . ",\n"; } $meta .= ");\n"; $writeResult = sugar_file_put_contents($this->customFilePath, $meta); $this->assertGreaterThan(0, $writeResult, 'there was an error writing custom popup meta to file using this path: ' . $this->customFilePath); //create new instance of popupmetadata parser $parserFactory = new ParserFactory(); $parser = $parserFactory->getParser(MB_POPUPLIST, 'Users'); //run save to write out the file using the new array elements. $parser->handleSave(false); //assert the file still exists $this->assertTrue(is_file($this->customFilePath), ' PopupMetaDataParser::handleSave() could not write out the file as expected.'); //include the file again to get the new popup meta array include $this->customFilePath; $popupKeys = array_keys($popupMeta); //assert that one of the new elements is there $this->assertContains('whereStatement', $popupKeys, 'an element that was defined in addToReserve was not processed and save within PopupMetaDataParser::handleSave()'); //assert that the element that was written but not defined in 'addToReserve' is no longer there $this->assertNotContains('disappear', $popupKeys, 'an element that was added but NOT defined in addToReserve was incorrectly processed and saved within PopupMetaDataParser::handleSave().'); }
/** * Next, we'll attempt to update all of the remaining relate fields in the vardefs that have 'save' set in their * field_def Only the 'save' fields should be saved as some vardef entries today are not for display only purposes * and break the application if saved If the vardef has entries for field <a> of type relate, where a->id_name = * <b> and field <b> of type link then we receive a value for b from the MVC in the _REQUEST, and it should be set * in the bean as $this->$b * * @api * @see save_relationship_changes * * @param array $exclude any relationship's to exclude * * @return array the list of relationships that were added or removed successfully or if they were a failure */ protected function handle_remaining_relate_fields($exclude = []) { $modified_relationships = ['add' => ['success' => [], 'failure' => []], 'remove' => ['success' => [], 'failure' => []]]; foreach ($this->field_defs as $def) { if ($def['type'] == 'relate' && isset($def['id_name']) && isset($def['link']) && isset($def['save'])) { if (in_array($def['id_name'], $exclude) || in_array($def['id_name'], $this->relationship_fields)) { continue; } // continue to honor the exclude array and exclude any relationships that will be handled by the relationship_fields mechanism $linkField = $def['link']; if (isset($this->field_defs[$linkField])) { if ($this->load_relationship($linkField)) { $idName = $def['id_name']; if (!empty($this->rel_fields_before_value[$idName]) && empty($this->{$idName})) { //if before value is not empty then attempt to delete relationship Log::debug("save_relationship_changes(): From field_defs - attempting to remove the relationship record: {$def['link']} = {$this->rel_fields_before_value[$def['id_name']]}"); $success = $this->{$def}['link']->delete($this->id, $this->rel_fields_before_value[$def['id_name']]); // just need to make sure it's true and not an array as it's possible to return an array if ($success == true) { $modified_relationships['remove']['success'][] = $def['link']; } else { $modified_relationships['remove']['failure'][] = $def['link']; } Log::debug("save_relationship_changes(): From field_defs - attempting to remove the relationship record returned " . var_export_helper($success, true)); } if (!empty($this->{$idName}) && is_string($this->{$idName})) { Log::debug("save_relationship_changes(): From field_defs - attempting to add a relationship record - {$def['link']} = {$this->{$def}['id_name']}"); $success = $this->{$linkField}->add($this->{$idName}); // just need to make sure it's true and not an array as it's possible to return an array if ($success == true) { $modified_relationships['add']['success'][] = $linkField; } else { $modified_relationships['add']['failure'][] = $linkField; } Log::debug("save_relationship_changes(): From field_defs - add a relationship record returned " . var_export_helper($success, true)); } } else { Log::fatal("Failed to load relationship {$linkField} while saving {$this->module_dir}"); } } } } return $modified_relationships; }
/** * Takes in the request params from a save request and processes * them for the save. * * @param REQUEST params $params */ function saveDropDown($params) { $count = 0; $dropdown = array(); $dropdown_name = $params['dropdown_name']; $selected_lang = !empty($params['dropdown_lang']) ? $params['dropdown_lang'] : $_SESSION['authenticated_user_language']; $my_list_strings = return_app_list_strings_language($selected_lang); while (isset($params['slot_' . $count])) { $index = $params['slot_' . $count]; $key = isset($params['key_' . $index]) ? SugarCleaner::stripTags($params['key_' . $index]) : 'BLANK'; $value = isset($params['value_' . $index]) ? SugarCleaner::stripTags($params['value_' . $index]) : ''; if ($key == 'BLANK') { $key = ''; } $key = trim($key); $value = trim($value); if (empty($params['delete_' . $index])) { $dropdown[$key] = $value; } $count++; } if ($selected_lang == $GLOBALS['current_language']) { $GLOBALS['app_list_strings'][$dropdown_name] = $dropdown; } $contents = return_custom_app_list_strings_file_contents($selected_lang); //get rid of closing tags they are not needed and are just trouble $contents = str_replace("?>", '', $contents); if (empty($contents)) { $contents = "<?php"; } //add new drop down to the bottom if (!empty($params['use_push'])) { //this is for handling moduleList and such where nothing should be deleted or anything but they can be renamed foreach ($dropdown as $key => $value) { //only if the value has changed or does not exist do we want to add it this way if (!isset($my_list_strings[$dropdown_name][$key]) || strcmp($my_list_strings[$dropdown_name][$key], $value) != 0) { //clear out the old value $pattern_match = '/\\s*\\$app_list_strings\\s*\\[\\s*\'' . $dropdown_name . '\'\\s*\\]\\[\\s*\'' . $key . '\'\\s*\\]\\s*=\\s*[\'\\"]{1}.*?[\'\\"]{1};\\s*/ism'; $contents = preg_replace($pattern_match, "\n", $contents); //add the new ones $contents .= "\n\$app_list_strings['{$dropdown_name}']['{$key}']=" . var_export_helper($value) . ";"; } } } else { //clear out the old value $pattern_match = '/\\s*\\$app_list_strings\\s*\\[\\s*\'' . $dropdown_name . '\'\\s*\\]\\s*=\\s*array\\s*\\([^\\)]*\\)\\s*;\\s*/ism'; $contents = preg_replace($pattern_match, "\n", $contents); //add the new ones $contents .= "\n\$app_list_strings['{$dropdown_name}']=" . var_export_helper($dropdown) . ";"; } // Bug 40234 - If we have no contents, we don't write the file. Checking for "<?php" because above it's set to that if empty if ($contents != "<?php") { save_custom_app_list_strings_contents($contents, $selected_lang); sugar_cache_reset(); } // Bug38011 $repairAndClear = new RepairAndClear(); $repairAndClear->module_list = array(translate('LBL_ALL_MODULES')); $repairAndClear->show_output = false; $repairAndClear->clearJsLangFiles(); // ~~~~~~~~ }
/** * Write the theme metadata file. This method actually does: * - Read contents of base/default theme metadata file * - Override variables (if $resetBaseDefaultTheme is false) * - Save the file as the theme metadata file. * * @param bool $reset True if you want to reset the theme to the base default theme */ public function saveThemeVariables($reset = false) { // take the contents from /themes/clients/base/default/variables.php $baseDefaultTheme = new SidecarTheme('base', 'default'); $baseDefaultThemePaths = $baseDefaultTheme->getPaths(); include $baseDefaultThemePaths['base'] . 'variables.php'; if (is_dir($this->paths['cache'])) { rmdir_recursive($this->paths['cache']); } if ($reset) { //In case of reset we just need to delete the theme files. if (is_dir($this->paths['custom'])) { rmdir_recursive($this->paths['custom']); } } else { //override the base variables with variables passed in arguments foreach ($this->variables as $lessVar => $lessValue) { foreach ($lessdefs as $type => $varset) { if (isset($lessdefs[$type][$lessVar])) { $lessdefs[$type][$lessVar] = $lessValue; } } } // save the theme variables in /themes/clients/$client/$themeName/variables.php sugar_mkdir($this->paths['custom'], null, true); $write = "<?php\n" . '// created: ' . date('Y-m-d H:i:s') . "\n" . '$lessdefs = ' . var_export_helper($lessdefs) . ';'; sugar_file_put_contents($this->paths['custom'] . 'variables.php', $write); } }
function saveAvailibleSubpanelDef($panelName, $layout) { $dir = $this->getModuleDir() . "/metadata/subpanels"; $filepath = "{$dir}/{$panelName}.php"; if (mkdir_recursive($dir)) { // preserve any $module_name entry if one exists if (file_exists($filepath)) { include $filepath; } $module_name = isset($module_name) ? $module_name : $this->key_name; $layout = "<?php\n" . '$module_name=\'' . $module_name . "';\n" . '$subpanel_layout = ' . var_export_helper($layout) . ";"; $GLOBALS['log']->debug("About to save this file to {$filepath}"); $GLOBALS['log']->debug($layout); $fw = sugar_fopen($filepath, 'w'); fwrite($fw, $layout); fclose($fw); } }
function write_array_to_file($the_name, $the_array, $the_file, $mode = "w", $header = '') { if (!empty($header) && ($mode != 'a' || !file_exists($the_file))) { $the_string = $header; } else { $the_string = "<?php\n" . '// created: ' . date('Y-m-d H:i:s') . "\n"; } $the_string .= "\${$the_name} = " . var_export_helper($the_array) . ";"; return sugar_file_put_contents($the_file, $the_string, LOCK_EX) !== false; }
function getNewCustomContents($dropdown_name, $dropdown, $lang) { $contents = return_custom_app_list_strings_file_contents($lang); $contents = str_replace("?>", '', $contents); if (empty($contents)) { $contents = "<?php"; } $contents = preg_replace($this->getPatternMatch($dropdown_name), "\n", $contents); $contents .= "\n\$GLOBALS['app_list_strings']['{$dropdown_name}']=" . var_export_helper($dropdown) . ";"; return $contents; }
/** * fix_dropdown_list * This method attempts to fix dropdown lists that were incorrectly named. * There were versions of SugarCRM that did not enforce naming convention rules * for the dropdown list field name. This method attempts to resolve that by * fixing the language files that may have been affected and then updating the * fields_meta_data table accordingly. It also refreshes any vardefs that may * have been affected. * */ function fix_dropdown_list() { if (file_exists('custom/include/language')) { $files = array(); $affected_modules = array(); $affected_keys = array(); getFiles($files, 'custom/include/language', '/\\.php$/i'); foreach ($files as $file) { if (file_exists($file . '.bak')) { $bak_mod_time = filemtime($file . '.bak'); $php_mod_time = filemtime($file); //We're saying if the .php file was modified 30 seconds no more than php.bak file then we //run these additional cleanup checks if ($php_mod_time - $bak_mod_time < 30) { $app_list_strings = array(); $GLOBALS['app_list_strings'] = array(); require $file . '.bak'; $bak_app_list_strings = array_merge($app_list_strings, $GLOBALS['app_list_strings']); $app_list_strings = array(); $GLOBALS['app_list_strings'] = array(); require $file; $php_app_list_strings = array_merge($app_list_strings, $GLOBALS['app_list_strings']); //Get the file contents $contents = file_get_contents($file); //Now simulate a fix for the file before we compare w/ the .php file //we also append to the $contents foreach ($bak_app_list_strings as $key => $entry) { if (preg_match('/([^A-Za-z_])/', $key, $matches) && is_array($entry)) { $new_key = preg_replace('/[^A-Za-z_]/', '_', $key); $bak_app_list_strings[$new_key] = $bak_app_list_strings[$key]; unset($bak_app_list_strings[$key]); //Now if the entry doesn't exists in the .php file, then add to contents if (!isset($php_app_list_strings[$new_key])) { $contents .= "\n\$GLOBALS['app_list_strings']['{$new_key}'] = " . var_export_helper($bak_app_list_strings[$new_key]) . ";"; } } //if } //foreach //Now load the .php file to do the comparison foreach ($php_app_list_strings as $key => $entry) { if (isset($bak_app_list_strings[$key])) { $diff = array_diff($bak_app_list_strings[$key], $entry); if (!empty($diff)) { //There is a difference, so copy the $bak_app_list_strings version into the .php file $contents .= "\n\$GLOBALS['app_list_strings']['{$key}'] = " . var_export_helper($bak_app_list_strings[$key]) . ";"; } //if } //if } //foreach //Now write out the file contents //Create backup just in case copy($file, $file . '.php_bak'); $fp = @sugar_fopen($file, 'w'); if ($fp) { fwrite($fp, $contents); fclose($fp); } else { $GLOBALS['log']->error("Unable to update file contents in fix_dropdown_list for {$file}"); } //if-else } } unset($GLOBALS['app_strings']); unset($GLOBALS['app_list_strings']); $app_list_strings = array(); require $file; $touched = false; $contents = file_get_contents($file); if (!isset($GLOBALS['app_list_strings'])) { $GLOBALS['app_list_strings'] = $app_list_strings; } else { $GLOBALS['app_list_strings'] = array_merge($app_list_strings, $GLOBALS['app_list_strings']); } if (isset($GLOBALS['app_list_strings']) && is_array($GLOBALS['app_list_strings'])) { foreach ($GLOBALS['app_list_strings'] as $key => $entry) { if (preg_match('/([^A-Za-z_])/', $key, $matches) && is_array($entry)) { $result = $GLOBALS['db']->query("SELECT custom_module FROM fields_meta_data WHERE ext1 = '{$key}'"); if (!empty($result)) { while ($row = $GLOBALS['db']->fetchByAssoc($result)) { $custom_module = $row['custom_module']; if (!empty($GLOBALS['beanList'][$custom_module])) { $affected_modules[$custom_module] = $GLOBALS['beanList'][$custom_module]; } } //while } //Replace all invalid characters with '_' character $new_key = preg_replace('/[^A-Za-z_]/', '_', $key); $affected_keys[$key] = $new_key; $GLOBALS['app_list_strings'][$new_key] = $GLOBALS['app_list_strings'][$key]; unset($GLOBALS['app_list_strings'][$key]); $pattern_match = "/(\\[\\s*\\'{$key}\\'\\s*\\])/"; $new_key = "['{$new_key}']"; $out = preg_replace($pattern_match, $new_key, $contents); $contents = $out; $touched = true; } //if } //foreach //This is a check for g => h instances where the file contents were incorrectly written //and also fixes the scenario where via a UI upgrade, the app_list_strings were incorrectly //merged with app_list_strings variables declared elsewhere if (!$touched) { if (preg_match('/\\$GLOBALS\\s*\\[\\s*[\\"|\']app_list_strings[\\"|\']\\s*\\]\\s*=\\s*array\\s*\\(/', $contents)) { //Now also remove all the non-custom labels that were added if (preg_match('/language\\/([^\\.]+)\\.lang\\.php$/', $file, $matches)) { $language = $matches[1]; $app_list_strings = array(); if (file_exists("include/language/{$language}.lang.php")) { include "include/language/{$language}.lang.php"; } if (file_exists("include/language/{$language}.lang.override.php")) { $app_list_strings = _mergeCustomAppListStrings("include/language/{$language}.lang.override.php", $app_list_strings); } if (file_exists("custom/application/Ext/Language/{$language}.ext.lang.php")) { $app_list_strings = _mergeCustomAppListStrings("custom/application/Ext/Language/{$language}.ext.lang.php", $app_list_strings); } if (file_exists("custom/application/Ext/Language/{$language}.lang.ext.php")) { $app_list_strings = _mergeCustomAppListStrings("custom/application/Ext/Language/{$language}.lang.ext.php", $app_list_strings); } $all_non_custom_include_language_strings = $app_strings; $all_non_custom_include_language_list_strings = $app_list_strings; $unset_keys = array(); if (!empty($GLOBALS['app_list_strings'])) { foreach ($GLOBALS['app_list_strings'] as $key => $value) { $diff = array(); if (isset($all_non_custom_include_language_list_strings[$key])) { $diff = array_diff($all_non_custom_include_language_list_strings[$key], $GLOBALS['app_list_strings'][$key]); } if (!empty($all_non_custom_include_language_list_strings[$key]) && empty($diff)) { $unset_keys[] = $key; } } } foreach ($unset_keys as $key) { unset($GLOBALS['app_list_strings'][$key]); } if (!empty($GLOBALS['app_strings'])) { foreach ($GLOBALS['app_strings'] as $key => $value) { if (!empty($all_non_custom_include_language_strings[$key])) { unset($GLOBALS['app_strings'][$key]); } } } } //if(preg_match...) $out = "<?php \n"; if (!empty($GLOBALS['app_strings'])) { foreach ($GLOBALS['app_strings'] as $key => $entry) { $out .= "\n\$GLOBALS['app_strings']['{$key}']=" . var_export_helper($entry) . ";"; } } foreach ($GLOBALS['app_list_strings'] as $key => $entry) { $out .= "\n\$GLOBALS['app_list_strings']['{$key}']=" . var_export_helper($entry) . ";"; } //foreach $touched = true; } //if(preg_match...) } //if(!$touched) if ($touched) { //Create a backup just in case copy($file, $file . '.bak'); $fp = @sugar_fopen($file, 'w'); if ($fp) { fwrite($fp, $out); fclose($fp); } else { //If we can't update the file, just return $GLOBALS['log']->error("Unable to update file contents in fix_dropdown_list."); return; } } //if($touched) } //if } //foreach($files) //Update db entries (the order matters here... need to process database changes first) if (!empty($affected_keys)) { foreach ($affected_keys as $old_key => $new_key) { $GLOBALS['db']->query("UPDATE fields_meta_data SET ext1 = '{$new_key}' WHERE ext1 = '{$old_key}'"); } } //Update vardef files for affected modules if (!empty($affected_modules)) { foreach ($affected_modules as $module => $object) { VardefManager::refreshVardefs($module, $object); } } } }
/** * @param array $hook_array * * @return string */ function build_logic_file($hook_array) { $hook_contents = ""; $hook_contents .= "// Do not store anything in this file that is not part of the array or the hook version. This file will" . PHP_EOL; $hook_contents .= "// be automatically rebuilt in the future." . PHP_EOL . PHP_EOL; $hook_contents .= "\$hook_version = 1;" . PHP_EOL; $hook_contents .= "\$hook_array = [];" . PHP_EOL; foreach ($hook_array as $event_array => $event) { $hook_contents .= "\$hook_array['" . $event_array . "'] = [];" . PHP_EOL; foreach ($event as $second_key => $elements) { $hook_contents .= "\$hook_array['" . $event_array . "'][] = "; $hook_contents .= "["; foreach ($elements as $element) { $hook_contents .= ", " . var_export_helper($element); } $hook_contents .= "];" . PHP_EOL; } } return $hook_contents . PHP_EOL . PHP_EOL; }
/** * puts connector data in cache * @param array $data */ public function putConnectorCache($data) { // Create the cache directory if need be // fix for the cache/api/metadata problem $cacheDir = 'api/metadata'; mkdir_recursive(sugar_cached($cacheDir)); // Handle the cache file $cacheFile = sugar_cached('api/metadata/connectors.php'); $write = "<?php\n" . '// created: ' . date('Y-m-d H:i:s') . "\n" . '$connectors = ' . var_export_helper($data) . ';'; // Write with atomic writing to prevent issues with simultaneous requests // for this file sugar_file_put_contents_atomic($cacheFile, $write); if (!empty($data['_hash'])) { $this->addToHash('connectors', $data['_hash']); } }
function exportProjectInstall($package, $for_export) { $pre = $for_export ? MB_EXPORTPREPEND : ""; $installdefs = array('id' => $pre . $this->name); $installdefs['copy'][] = array('from' => '<basepath>/' . $this->name, 'to' => 'custom/modulebuilder/packages/' . $this->name); return "\n" . '$installdefs = ' . var_export_helper($installdefs) . ';'; }
protected function saveVardefs($basepath, $installDefPrefix, $relationshipName, $vardefs) { mkdir_recursive("{$basepath}/vardefs/"); $GLOBALS['log']->debug(get_class($this) . "->saveVardefs(): vardefs =" . print_r($vardefs, true)); foreach ($vardefs as $moduleName => $definitions) { // find this module's Object name - the object name, not the module name, is used as the key in the vardefs... if (isset($GLOBALS['beanList'][$moduleName])) { $module = get_module_info($moduleName); $object = $module->object_name; } else { $object = $moduleName; } $relName = $moduleName; foreach ($definitions as $definition) { if (!empty($definition['relationship'])) { $relName = $definition['relationship']; break; } } $filename = "{$basepath}/vardefs/{$relName}_{$moduleName}.php"; $out = "<?php\n// created: " . date('Y-m-d H:i:s') . "\n"; foreach ($definitions as $definition) { $GLOBALS['log']->debug(get_class($this) . "->saveVardefs(): saving the following to {$filename}" . print_r($definition, true)); $out .= '$dictionary["' . $object . '"]["fields"]["' . $definition['name'] . '"] = ' . var_export_helper($definition) . ";\n"; } file_put_contents($filename, $out); $installDefs[$moduleName] = array('from' => "{$installDefPrefix}/relationships/vardefs/{$relName}_{$moduleName}.php", 'to_module' => $moduleName); } $GLOBALS['log']->debug(get_class($this) . "->saveVardefs(): installDefs =" . print_r($installDefs, true)); return $installDefs; }
function write_array_to_file($the_name, $the_array, $the_file, $mode = "w", $header = '') { if (!empty($header) && ($mode != 'a' || !file_exists($the_file))) { $the_string = $header; } else { $the_string = "<?php\n" . '// created: ' . date('Y-m-d H:i:s') . "\n"; } $the_string .= "\${$the_name} = " . var_export_helper($the_array) . ";\n?>\n"; if ($fh = @sugar_fopen($the_file, $mode)) { fputs($fh, $the_string); fclose($fh); return true; } else { return false; } }