/** * Builds the cache of Dashlets by scanning the system */ function buildCache() { global $beanList; $dashletFiles = array(); $dashletFilesCustom = array(); getFiles($dashletFiles, 'modules', '/^.*\\/Dashlets\\/[^\\.]*\\.php$/'); getFiles($dashletFilesCustom, 'custom/modules', '/^.*\\/Dashlets\\/[^\\.]*\\.php$/'); $cacheDir = create_cache_directory('dashlets/'); $allDashlets = array_merge($dashletFiles, $dashletFilesCustom); $dashletFiles = array(); foreach ($allDashlets as $num => $file) { if (substr_count($file, '.meta') == 0) { // ignore meta data files $class = substr($file, strrpos($file, '/') + 1, -4); $dashletFiles[$class] = array(); $dashletFiles[$class]['file'] = $file; $dashletFiles[$class]['class'] = $class; if (is_file(preg_replace('/(.*\\/.*)(\\.php)/Uis', '$1.meta$2', $file))) { // is there an associated meta data file? $dashletFiles[$class]['meta'] = preg_replace('/(.*\\/.*)(\\.php)/Uis', '$1.meta$2', $file); require $dashletFiles[$class]['meta']; if (isset($dashletMeta[$class]['module'])) { $dashletFiles[$class]['module'] = $dashletMeta[$class]['module']; } } $filesInDirectory = array(); getFiles($filesInDirectory, substr($file, 0, strrpos($file, '/')), '/^.*\\/Dashlets\\/[^\\.]*\\.icon\\.(jpg|jpeg|gif|png)$/i'); if (!empty($filesInDirectory)) { $dashletFiles[$class]['icon'] = $filesInDirectory[0]; // take the first icon we see } } } write_array_to_file('dashletsFiles', $dashletFiles, $cacheDir . 'dashlets.php'); }
static function buildActionCache($silent = true) { if (!is_dir(ActionFactory::$action_directory)) { return false; } // First get a list of all the files in this directory. $entries = array(); $actions = array(); $javascript = ""; foreach (SugarAutoLoader::getFilesCustom(ActionFactory::$action_directory) as $path) { $entry = basename($path); if (strtolower(substr($entry, -4)) != ".php" || in_array($entry, ActionFactory::$exclude_files)) { continue; } require_once $path; $className = substr($entry, 0, strlen($entry) - 4); $actionName = call_user_func(array($className, "getActionName")); $actions[$actionName] = array('class' => $className, 'file' => $path); $javascript .= call_user_func(array($className, "getJavascriptClass")); if (!$silent) { echo "added action {$actionName} <br/>"; } } if (empty($actions)) { return ""; } create_cache_directory("Expressions/actions_cache.php"); write_array_to_file('actions', $actions, sugar_cached('Expressions/actions_cache.php')); ActionFactory::$loaded_actions = $actions; return $javascript; }
function UploadFile($field_name) { // $field_name is the name of your passed file selector field in your form // i.e., for Emails, it is "email_attachmentX" where X is 0-9 $this->field_name = $field_name; // Bug 28408 - Add automatic creation of upload cache directory if it doesn't exist if (!is_dir($GLOBALS['sugar_config']['upload_dir'])) { create_cache_directory(str_replace($GLOBALS['sugar_config']['cache_dir'], '', $GLOBALS['sugar_config']['upload_dir'])); } }
/** * Returns the filename for a temporary file * * @param string $type string to prepend to the filename, typically to indicate the file's use * @return string filename */ private static function _createFileName($type = 'misc') { global $sugar_config, $current_user; if (!is_dir($sugar_config['import_dir'])) { create_cache_directory(preg_replace('/^cache\\//', '', $sugar_config['import_dir'])); } if (!is_writable($sugar_config['import_dir'])) { return false; } return "{$sugar_config['import_dir']}{$type}_{$current_user->id}.csv"; }
function createModuleStringsCache($moduleDir, $lang = 'en_us') { $json = getJSONobj(); // cn: bug 8242 - non-US langpack chokes $mod_strings = return_module_language($lang, $moduleDir); $mod_strings_encoded = $json->encode($mod_strings); $str = "SUGAR.language.setLanguage('" . $moduleDir . "', " . $mod_strings_encoded . ");"; $cacheDir = create_cache_directory('jsLanguage/' . $moduleDir . '/'); if ($fh = @fopen($cacheDir . $lang . '.js', "w")) { fputs($fh, $str); fclose($fh); } }
protected function action_getImageMap() { ob_start(); global $current_user; if (!isset($_REQUEST['imageMapId'])) { return; } require_once 'modules/AOR_Charts/lib/pChart/pChart.php'; $img = new pImage(100, 100); $imageMapDir = create_cache_directory('modules/AOR_Charts/ImageMap/' . $current_user->id . '/'); $id = $current_user->id . "-" . (int) $_REQUEST['imageMapId']; ob_clean(); $img->dumpImageMap($id, IMAGE_MAP_STORAGE_FILE, $id, $imageMapDir); }
public function testcreate_cache_directory() { //execute the method and test if it created file/dir exists $cache_dir = rtrim($GLOBALS['sugar_config']['cache_dir'], '/\\'); $file = 'Test/'; if ($this->rootFs->hasChild($file) == true) { rmdir($cache_dir . '/' . $file); } $actual = create_cache_directory($file); $this->assertFileExists($actual); if ($this->rootFs->hasChild($file) == true) { rmdir($cache_dir . '/' . $file); } }
function __construct() { global $sugar_config; $config = HTMLPurifier_Config::createDefault(); if (!is_dir(sugar_cached("htmlclean"))) { create_cache_directory("htmlclean/"); } $config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); $config->set('Core.Encoding', 'UTF-8'); $hidden_tags = array('script' => true, 'style' => true, 'title' => true, 'head' => true); $config->set('Core.HiddenElements', $hidden_tags); $config->set('Cache.SerializerPath', sugar_cached("htmlclean")); $config->set('URI.Base', $sugar_config['site_url']); $config->set('CSS.Proprietary', true); $config->set('HTML.TidyLevel', 'light'); $config->set('HTML.ForbiddenElements', array('body' => true, 'html' => true)); $config->set('AutoFormat.RemoveEmpty', false); $config->set('Cache.SerializerPermissions', 0775); // for style //$config->set('Filter.ExtractStyleBlocks', true); $config->set('Filter.ExtractStyleBlocks.TidyImpl', false); // can't use csstidy, GPL if (!empty($GLOBALS['sugar_config']['html_allow_objects'])) { // for object $config->set('HTML.SafeObject', true); // for embed $config->set('HTML.SafeEmbed', true); } $config->set('Output.FlashCompat', true); // for iframe and xmp $config->set('Filter.Custom', array(new HTMLPurifier_Filter_Xmp())); // for link $config->set('HTML.DefinitionID', 'Sugar HTML Def'); $config->set('HTML.DefinitionRev', 2); $config->set('Cache.SerializerPath', sugar_cached('htmlclean/')); // IDs are namespaced $config->set('Attr.EnableID', true); $config->set('Attr.IDPrefix', 'sugar_text_'); if ($def = $config->maybeGetRawHTMLDefinition()) { $form = $def->addElement('link', 'Flow', 'Empty', 'Core', array('href*' => 'URI', 'rel' => 'Enum#stylesheet', 'type' => 'Enum#text/css')); $iframe = $def->addElement('iframe', 'Flow', 'Optional: #PCDATA | Flow | Block', 'Core', array('src*' => 'URI', 'frameborder' => 'Enum#0,1', 'marginwidth' => 'Pixels', 'marginheight' => 'Pixels', 'scrolling' => 'Enum#|yes,no,auto', 'align' => 'Enum#top,middle,bottom,left,right,center', 'height' => 'Length', 'width' => 'Length')); $iframe->excludes = array('iframe'); } $uri = $config->getDefinition('URI'); $uri->addFilter(new SugarURIFilter(), $config); HTMLPurifier_URISchemeRegistry::instance()->register('cid', new HTMLPurifier_URIScheme_cid()); $this->purifier = new HTMLPurifier($config); }
public function createModuleStringsCache($moduleDir, $lang = 'en_us', $return = false) { global $mod_strings; $json = getJSONobj(); // cn: bug 8242 - non-US langpack chokes // Allows for modification of mod_strings by individual modules prior to // sending down to JS if (empty($mod_strings)) { $mod_strings = return_module_language($lang, $moduleDir); } $mod_strings_encoded = $json->encode($mod_strings); $str = "SUGAR.language.setLanguage('" . $moduleDir . "', " . $mod_strings_encoded . ");"; $cacheDir = create_cache_directory('jsLanguage/' . $moduleDir . '/'); if ($fh = @fopen($cacheDir . $lang . '.js', "w")) { fputs($fh, $str); fclose($fh); } if ($return) { return $str; } }
/** * Returns the URL for an image in the current theme. If not found in the current theme, will revert * to looking in the base theme. * * @param string $jsFileName js file name * @param bool $returnURL if true, returns URL with unique image mark, otherwise returns path to the file * @return string path to js file */ public function getJSURL($jsFileName, $returnURL = true) { if (isset($this->_jsCache[$jsFileName]) && sugar_is_file(sugar_cached($this->_jsCache[$jsFileName]))) { if ($returnURL) { return getJSPath("cache/" . $this->_jsCache[$jsFileName]); } else { return sugar_cached($this->_jsCache[$jsFileName]); } } $jsFileContents = ''; $fullFileName = $this->getJSPath() . '/' . $jsFileName; $defaultFileName = $this->getDefaultJSPath() . '/' . $jsFileName; if (isset($this->parentTheme) && SugarThemeRegistry::get($this->parentTheme) instanceof SugarTheme && ($filename = SugarThemeRegistry::get($this->parentTheme)->getJSURL($jsFileName, false)) != '' && !in_array($jsFileName, $this->ignoreParentFiles)) { $jsFileContents .= file_get_contents($filename); } else { if (sugar_is_file($defaultFileName)) { $jsFileContents .= file_get_contents($defaultFileName); } if (sugar_is_file('custom/' . $defaultFileName)) { $jsFileContents .= file_get_contents('custom/' . $defaultFileName); } } if (sugar_is_file($fullFileName)) { $jsFileContents .= file_get_contents($fullFileName); } if (sugar_is_file('custom/' . $fullFileName)) { $jsFileContents .= file_get_contents('custom/' . $fullFileName); } if (empty($jsFileContents)) { $GLOBALS['log']->warn("Javascript File {$jsFileName} not found"); return false; } // create the cached file location $jsFilePath = create_cache_directory($fullFileName); // minify the js if (!inDeveloperMode() && !sugar_is_file(str_replace('.js', '-min.js', $jsFilePath))) { $jsFileContents = SugarMin::minify($jsFileContents); $jsFilePath = str_replace('.js', '-min.js', $jsFilePath); $fullFileName = str_replace('.js', '-min.js', $fullFileName); } // now write the js to cache sugar_file_put_contents($jsFilePath, $jsFileContents); $this->_jsCache[$jsFileName] = $fullFileName; if ($returnURL) { return getJSPath("cache/" . $fullFileName); } return sugar_cached($fullFileName); }
function saveCache($module, $lang, $loaded_mod_strings, $additonal_objects = array()) { if (empty($lang)) { $lang = $GLOBALS['sugar_config']['default_language']; } $file = create_cache_directory('modules/' . $module . '/language/' . $lang . '.lang.php'); write_array_to_file('mod_strings', $loaded_mod_strings, $file); include $file; // put the item in the sugar cache. $key = self::getLanguageCacheKey($module, $lang); sugar_cache_put($key, $loaded_mod_strings); }
/** * This method fill the fontList with all the fonts available */ public function listFontFiles() { $this->fontList = array(); if (file_exists($cachedfile = sugar_cached("Sugarpdf/cachedFontList.php"))) { require $cachedfile; $this->fontList = $cachedFontList; return true; } else { if ($this->parseFolder()) { $cacheDir = create_cache_directory('Sugarpdf/'); write_array_to_file('cachedFontList', $this->fontList, $cacheDir . 'cachedFontList.php'); return true; } } return false; }
/** * Returns an input control for this fieldname given * * @param string $module * @param string $fieldname * @param string $vardef * @param string $value * @return string html for input element for this control */ function getControl($module, $fieldname, $vardef = null, $value = '') { global $current_language, $app_strings, $dictionary, $app_list_strings; // use the mod_strings for this module $mod_strings = return_module_language($current_language, $module); // set the filename for this control $file = create_cache_directory('modules/Import/') . $module . $fieldname . '.tpl'; if (!is_file($file) || !empty($GLOBALS['sugar_config']['developerMode']) || !empty($_SESSION['developerMode'])) { if (!isset($vardef)) { $focus = loadBean($module); $vardef = $focus->getFieldDefinition($fieldname); } // if this is the id relation field, then don't have a pop-up selector. if ($vardef['type'] == 'relate' && $vardef['id_name'] == $vardef['name']) { $vardef['type'] = 'varchar'; } // create the dropdowns for the parent type fields if ($vardef['type'] == 'parent_type') { $vardef['type'] = 'enum'; } // remove the special text entry field function 'getEmailAddressWidget' if (isset($vardef['function']) && ($vardef['function'] == 'getEmailAddressWidget' || $vardef['function']['name'] == 'getEmailAddressWidget')) { unset($vardef['function']); } // load SugarFieldHandler to render the field tpl file static $sfh; if (!isset($sfh)) { require_once 'include/SugarFields/SugarFieldHandler.php'; $sfh = new SugarFieldHandler(); } $displayParams = array(); $displayParams['formName'] = 'importstep3'; $contents = $sfh->displaySmarty('fields', $vardef, 'ImportView', $displayParams); // Remove all the copyright comments $contents = preg_replace('/\\{\\*[^\\}]*?\\*\\}/', '', $contents); // hack to disable one of the js calls in this control if (isset($vardef['function']) && ($vardef['function'] == 'getCurrencyDropDown' || $vardef['function']['name'] == 'getCurrencyDropDown')) { $contents .= "{literal}<script>function CurrencyConvertAll() { return; }</script>{/literal}"; } // Save it to the cache file if ($fh = @sugar_fopen($file, 'w')) { fputs($fh, $contents); fclose($fh); } } // Now render the template we received $ss = new Sugar_Smarty(); // Create Smarty variables for the Calendar picker widget global $timedate; $time_format = $timedate->get_user_time_format(); $date_format = $timedate->get_cal_date_format(); $ss->assign('USER_DATEFORMAT', $timedate->get_user_date_format()); $ss->assign('TIME_FORMAT', $time_format); $time_separator = ":"; $match = array(); if (preg_match('/\\d+([^\\d])\\d+([^\\d]*)/s', $time_format, $match)) { $time_separator = $match[1]; } $t23 = strpos($time_format, '23') !== false ? '%H' : '%I'; if (!isset($match[2]) || $match[2] == '') { $ss->assign('CALENDAR_FORMAT', $date_format . ' ' . $t23 . $time_separator . "%M"); } else { $pm = $match[2] == "pm" ? "%P" : "%p"; $ss->assign('CALENDAR_FORMAT', $date_format . ' ' . $t23 . $time_separator . "%M" . $pm); } // populate the fieldlist from the vardefs $fieldlist = array(); if (!isset($focus) || !$focus instanceof SugarBean) { $focus = loadBean($module); } // create the dropdowns for the parent type fields if ($vardef['type'] == 'parent_type') { $focus->field_defs[$vardef['name']]['options'] = $focus->field_defs[$vardef['group']]['options']; } $vardefFields = $focus->getFieldDefinitions(); foreach ($vardefFields as $name => $properties) { $fieldlist[$name] = $properties; // fill in enums if (isset($fieldlist[$name]['options']) && is_string($fieldlist[$name]['options']) && isset($app_list_strings[$fieldlist[$name]['options']])) { $fieldlist[$name]['options'] = $app_list_strings[$fieldlist[$name]['options']]; } elseif (isset($fieldlist[$name]['options']) && is_string($fieldlist[$name]['options']) && isset($mod_strings[$fieldlist[$name]['options']])) { $fieldlist[$name]['options'] = $mod_strings[$fieldlist[$name]['options']]; } // Bug 22730: make sure all enums have the ability to select blank as the default value. if (!isset($fieldlist[$name]['options'][''])) { $fieldlist[$name]['options'][''] = ''; } } // fill in function return values if (!in_array($fieldname, array('email1', 'email2'))) { if (!empty($fieldlist[$fieldname]['function']['returns']) && $fieldlist[$fieldname]['function']['returns'] == 'html') { $function = $fieldlist[$fieldname]['function']['name']; // include various functions required in the various vardefs if (isset($fieldlist[$fieldname]['function']['include']) && is_file($fieldlist[$fieldname]['function']['include'])) { require_once $fieldlist[$fieldname]['function']['include']; } $value = $function($focus, $fieldname, $value, 'EditView'); // Bug 22730 - add a hack for the currency type dropdown, since it's built by a function. if (preg_match('/getCurrency.*DropDown/s', $function)) { $value = str_ireplace('</select>', '<option value="">' . $app_strings['LBL_NONE'] . '</option></select>', $value); } } elseif ($fieldname == 'assigned_user_name' && empty($value)) { $fieldlist['assigned_user_id']['value'] = $GLOBALS['current_user']->id; $value = get_assigned_user_name($GLOBALS['current_user']->id); } elseif ($fieldname == 'team_name' && empty($value)) { $value = json_encode(array()); } } $fieldlist[$fieldname]['value'] = $value; $ss->assign("fields", $fieldlist); $ss->assign("form_name", 'importstep3'); $ss->assign("bean", $focus); // add in any additional strings $ss->assign("MOD", $mod_strings); $ss->assign("APP", $app_strings); return $ss->fetch($file); }
/** * Save the dictionary object to the cache * @param string $module the name of the module * @param string $object the name of the object */ static function saveCache($module, $object, $additonal_objects = array()) { if (empty($GLOBALS['dictionary'][$object])) { $object = BeanFactory::getObjectName($module); } $file = create_cache_directory('modules/' . $module . '/' . $object . 'vardefs.php'); $out = "<?php \n \$GLOBALS[\"dictionary\"][\"" . $object . "\"]=" . var_export($GLOBALS['dictionary'][$object], true) . ";"; sugar_file_put_contents_atomic($file, $out); if (sugar_is_file($file) && is_readable($file)) { include $file; } // put the item in the sugar cache. $key = "VardefManager.{$module}.{$object}"; //Sometimes bad definitions can get in from left over extensions or file system lag(caching). We need to clean those. $data = self::cleanVardefs($GLOBALS['dictionary'][$object]); sugar_cache_put($key, $data); }
/** * Builds a template * This is a private function that should be called only from checkTemplate method * * @param module string module name * @param view string view need (eg DetailView, EditView, etc) * @param tpl string generic tpl to use * @param ajaxSave boolean parameter indicating whether or not this is coming from an Ajax call * @param metaDataDefs metadata definition as Array **/ function buildTemplate($module, $view, $tpl, $ajaxSave, $metaDataDefs) { $this->loadSmarty(); $cacheDir = create_cache_directory($this->templateDir . $module . '/'); $file = $cacheDir . $view . '.tpl'; $string = '{* Create Date: ' . date('Y-m-d H:i:s') . "*}\n"; $this->ss->left_delimiter = '{{'; $this->ss->right_delimiter = '}}'; $this->ss->assign('module', $module); $this->ss->assign('built_in_buttons', array('CANCEL', 'DELETE', 'DUPLICATE', 'EDIT', 'FIND_DUPLICATES', 'SAVE', 'CONNECTOR')); $contents = $this->ss->fetch($tpl); //Insert validation and quicksearch stuff here if ($view == 'EditView' || strpos($view, 'QuickCreate') || $ajaxSave || $view == "ConvertLead") { global $dictionary, $beanList, $app_strings, $mod_strings; $mod = $beanList[$module]; if ($mod == 'aCase') { $mod = 'Case'; } $defs = $dictionary[$mod]['fields']; $defs2 = array(); //Retrieve all panel field definitions with displayParams Array field set $panelFields = array(); foreach ($metaDataDefs['panels'] as $panel) { foreach ($panel as $row) { foreach ($row as $entry) { if (empty($entry)) { continue; } if (is_array($entry) && isset($entry['name']) && isset($entry['displayParams']) && isset($entry['displayParams']['required']) && $entry['displayParams']['required']) { $panelFields[$entry['name']] = $entry; } if (is_array($entry)) { $defs2[$entry['name']] = $entry; } else { $defs2[$entry] = array('name' => $entry); } } //foreach } //foreach } //foreach foreach ($panelFields as $field => $value) { $nameList = array(); if (!is_array($value['displayParams']['required'])) { $nameList[] = $field; } else { foreach ($value['displayParams']['required'] as $groupedField) { $nameList[] = $groupedField; } } foreach ($nameList as $x) { if (isset($defs[$x]) && isset($defs[$x]['type']) && !isset($defs[$x]['required'])) { $defs[$x]['required'] = true; } } } //foreach //Create a base class with field_name_map property $sugarbean = new stdClass(); $sugarbean->field_name_map = $defs; $sugarbean->module_dir = $module; $javascript = new javascript(); $view = $view == 'QuickCreate' ? "QuickCreate_{$module}" : $view; $javascript->setFormName($view); $javascript->setSugarBean($sugarbean); if ($view != "ConvertLead") { $javascript->addAllFields('', null, true); } $validatedFields = array(); $javascript->addToValidateBinaryDependency('assigned_user_name', 'alpha', $javascript->buildStringToTranslateInSmarty('ERR_SQS_NO_MATCH_FIELD') . ': ' . $javascript->buildStringToTranslateInSmarty('LBL_ASSIGNED_TO'), 'false', '', 'assigned_user_id'); $validatedFields[] = 'assigned_user_name'; //Add remaining validation dependency for related fields //1) a relate type as defined in vardefs //2) set in metadata layout //3) not have validateDepedency set to false in metadata //4) have id_name in vardef entry //5) not already been added to Array foreach ($sugarbean->field_name_map as $name => $def) { if ($def['type'] == 'relate' && isset($defs2[$name]) && (!isset($defs2[$name]['validateDependency']) || $defs2[$name]['validateDependency'] === true) && isset($def['id_name']) && !in_array($name, $validatedFields)) { if (isset($mod_strings[$def['vname']]) || isset($app_strings[$def['vname']]) || translate($def['vname'], $sugarbean->module_dir) != $def['vname']) { $vname = $def['vname']; } else { $vname = "undefined"; } $javascript->addToValidateBinaryDependency($name, 'alpha', $javascript->buildStringToTranslateInSmarty('ERR_SQS_NO_MATCH_FIELD') . ': ' . $javascript->buildStringToTranslateInSmarty($vname), !empty($def['required']) ? 'true' : 'false', '', $def['id_name']); $validatedFields[] = $name; } } //foreach $contents .= "{literal}\n"; $contents .= $javascript->getScript(); $contents .= $this->createQuickSearchCode($defs, $defs2, $view, $module); $contents .= "{/literal}\n"; } else { if (preg_match('/^SearchForm_.+/', $view)) { global $dictionary, $beanList, $app_strings, $mod_strings; $mod = $beanList[$module]; if ($mod == 'aCase') { $mod = 'Case'; } $defs = $dictionary[$mod]['fields']; $contents .= '{literal}'; $contents .= $this->createQuickSearchCode($defs, array(), $view); $contents .= '{/literal}'; } } //if //Remove all the copyright comments $contents = preg_replace('/\\{\\*[^\\}]*?\\*\\}/', '', $contents); if ($fh = @sugar_fopen($file, 'w')) { fputs($fh, $contents); fclose($fh); } $this->ss->left_delimiter = '{'; $this->ss->right_delimiter = '}'; }
function get_trash_file($file) { require_once 'modules/DynamicLayout/DynamicLayoutUtils.php'; $delete_file = str_replace('.html', '.trash.php', $file); $delete_file = create_cache_directory($delete_file); $this->file = $delete_file; return $delete_file; }
require_once 'modules/MailMerge/MailMerge.php'; global $beanList, $beanFiles; $module = $_POST['mailmerge_module']; $document_id = $_POST['document_id']; $selObjs = urldecode($_POST['selected_objects_def']); $item_ids = array(); parse_str($selObjs, $item_ids); $class_name = $beanList[$module]; $includedir = $beanFiles[$class_name]; require_once $includedir; $seed = new $class_name(); $fields = get_field_list($seed); $document = new Document(); $document->retrieve($document_id); $items = array(); foreach ($item_ids as $key => $value) { $seed->retrieve($key); $items[] = $seed; } ini_set('max_execution_time', 600); ini_set('error_reporting', 'E_ALL'); $dataDir = create_cache_directory("MergedDocuments/"); $fileName = UploadFile::realpath("upload://{$document->document_revision_id}"); $outfile = pathinfo($document->filename, PATHINFO_FILENAME); $mm = new MailMerge(null, null, $dataDir); $mm->SetDataList($items); $mm->SetFieldList($fields); $mm->Template(array($fileName, $outfile)); $file = $mm->Execute(); $mm->CleanUp(); header("Location: index.php?module=MailMerge&action=Step4&file=" . urlencode($file));
/** * Check if we aren't running jobs too frequently * @return bool OK to run? */ public function throttle() { if ($this->min_interval == 0) { return true; } create_cache_directory($this->lockfile); if (!file_exists($this->lockfile)) { $this->markLastRun(); return true; } else { $ts = file_get_contents($this->lockfile); $this->markLastRun(); $now = time(); if ($now - $ts < $this->min_interval) { // run too frequently return false; } } return true; }
function executemd5($filesmd5, $md5calculated) { //BEGIN ALL MD5 CHECKS global $curdatetime; global $skip_md5_diff; global $sod_guid; if (file_exists('files.md5')) { include 'files.md5'; } //create dir for md5s $md5_directory = create_cache_directory("diagnostic/" . $sod_guid . "/diagnostic" . $curdatetime . "/md5/"); //skip this if the files.md5 didn't exist if (!$skip_md5_diff) { //make sure the files.md5 if ($filesmd5) { if (!copy('files.md5', $md5_directory . "files.md5")) { echo "Couldn't copy files.md5 to " . $md5_directory . "<br>Skipping md5 checks.<br>"; } } } $md5_string_calculated = generateMD5array('./'); if ($md5calculated) { write_array_to_file('md5_string_calculated', $md5_string_calculated, $md5_directory . "md5_array_calculated.php"); } //if the files.md5 didn't exist, we can't do this if (!$skip_md5_diff) { $md5_string_diff = array_diff($md5_string_calculated, $md5_string); write_array_to_file('md5_string_diff', $md5_string_diff, $md5_directory . "md5_array_diff.php"); } //END ALL MD5 CHECKS //BEGIN UPDATING PROGRESS BAR sodUpdateProgressBar(MD5_WEIGHT); //END UPDATING PROGRESS BAR }
/** * Returns the URL for an image in the current theme. If not found in the current theme, will revert * to looking in the base theme. * * @param string $jsFileName js file name * @param bool $addJSPath call getJSPath() with the results to add some unique image tracking support * @return string path to js file */ public function getJSURL($jsFileName, $addJSPath = true) { if (isset($this->_jsCache[$jsFileName])) { if ($addJSPath) { return getJSPath($this->_jsCache[$jsFileName]); } else { return $this->_jsCache[$jsFileName]; } } $jsFileContents = ''; if (isset($this->parentTheme) && SugarThemeRegistry::get($this->parentTheme) instanceof SugarTheme && ($filename = SugarThemeRegistry::get($this->parentTheme)->getJSURL($jsFileName, false)) != '') { $jsFileContents .= file_get_contents($filename); } else { if (sugar_is_file($this->getDefaultJSPath() . '/' . $jsFileName)) { $jsFileContents .= file_get_contents($this->getDefaultJSPath() . '/' . $jsFileName); } if (sugar_is_file('custom/' . $this->getDefaultJSPath() . '/' . $jsFileName)) { $jsFileContents .= file_get_contents('custom/' . $this->getDefaultJSPath() . '/' . $jsFileName); } } if (sugar_is_file($this->getJSPath() . '/' . $jsFileName)) { $jsFileContents .= file_get_contents($this->getJSPath() . '/' . $jsFileName); } if (sugar_is_file('custom/' . $this->getJSPath() . '/' . $jsFileName)) { $jsFileContents .= file_get_contents('custom/' . $this->getJSPath() . '/' . $jsFileName); } if (empty($jsFileContents)) { $GLOBALS['log']->warn("Javascript File {$jsFileName} not found"); return false; } // create the cached file location $jsFilePath = create_cache_directory($this->getJSPath() . "/{$jsFileName}"); // now write the js to cache sugar_file_put_contents($jsFilePath, $jsFileContents); // minify the js $jsFilePathMin = str_replace('.js', '-min.js', $jsFilePath); if (!inDeveloperMode() && !sugar_is_file($jsFilePathMin)) { $jMin = new JSMin($jsFilePath, $jsFilePathMin); $jMin->minify(); $jsFilePath = $jsFilePathMin; } $this->_jsCache[$jsFileName] = $jsFilePath; if ($addJSPath) { return getJSPath($jsFilePath); } return $jsFilePath; }
function cacheQuery($queryString, $resArray) { $file = create_cache_directory('modules/AOD_Index/QueryCache/' . md5($queryString)); $out = serialize($resArray); sugar_file_put_contents_atomic($file, $out); }
public function buildChartImage(array $reportData, array $fields, $asDataURI = true, $generateImageMapId = false) { global $current_user; require_once 'modules/AOR_Charts/lib/pChart/pChart.php'; if ($generateImageMapId !== false) { $generateImageMapId = $current_user->id . "-" . $generateImageMapId; } $html = ''; if (!in_array($this->type, $this->getValidChartTypes())) { return $html; } $x = $fields[$this->x_field]; $y = $fields[$this->y_field]; if (!$x || !$y) { //Malformed chart object - missing an axis field return ''; } $xName = str_replace(' ', '_', $x->label) . $this->x_field; $yName = str_replace(' ', '_', $y->label) . $this->y_field; $chartData = new pData(); $chartData->loadPalette("modules/AOR_Charts/lib/pChart/palettes/navy.color", TRUE); $labels = array(); foreach ($reportData as $row) { $chartData->addPoints($row[$yName], 'data'); $chartData->addPoints($row[$xName], 'Labels'); $labels[] = $row[$xName]; } $chartData->setSerieDescription("Months", "Month"); $chartData->setAbscissa("Labels"); $imageHeight = 700; $imageWidth = 700; $chartPicture = new pImage($imageWidth, $imageHeight, $chartData); if ($generateImageMapId) { $imageMapDir = create_cache_directory('modules/AOR_Charts/ImageMap/' . $current_user->id . '/'); $chartPicture->initialiseImageMap($generateImageMapId, IMAGE_MAP_STORAGE_FILE, $generateImageMapId, $imageMapDir); } $chartPicture->Antialias = True; $chartPicture->drawFilledRectangle(0, 0, $imageWidth - 1, $imageHeight - 1, array("R" => 240, "G" => 240, "B" => 240, "BorderR" => 0, "BorderG" => 0, "BorderB" => 0)); $chartPicture->setFontProperties(array("FontName" => "modules/AOR_Charts/lib/pChart/fonts/verdana.ttf", "FontSize" => 14)); $chartPicture->drawText($imageWidth / 2, 20, $this->name, array("R" => 0, "G" => 0, "B" => 0, 'Align' => TEXT_ALIGN_TOPMIDDLE)); $chartPicture->setFontProperties(array("FontName" => "modules/AOR_Charts/lib/pChart/fonts/verdana.ttf", "FontSize" => 6)); $chartPicture->setGraphArea(60, 60, $imageWidth - 60, $imageHeight - 100); switch ($this->type) { case 'radar': $this->buildChartImageRadar($chartPicture, $chartData, !empty($generateImageMapId)); break; case 'pie': $this->buildChartImagePie($chartPicture, $chartData, $reportData, $imageHeight, $imageWidth, $xName, !empty($generateImageMapId)); break; case 'line': $this->buildChartImageLine($chartPicture, !empty($generateImageMapId)); break; case 'bar': default: $this->buildChartImageBar($chartPicture, !empty($generateImageMapId)); break; } if ($generateImageMapId) { $chartPicture->replaceImageMapTitle("data", $labels); } ob_start(); $chartPicture->render(''); $img = ob_get_clean(); if ($asDataURI) { return 'data:image/png;base64,' . base64_encode($img); } else { return $img; } }
/** * Save the dictionary object to the cache * @param string $module the name of the module * @param string $object the name of the object */ function saveCache($module, $object, $additonal_objects = array()) { $file = create_cache_directory('modules/' . $module . '/' . $object . 'vardefs.php'); write_array_to_file('GLOBALS["dictionary"]["' . $object . '"]', $GLOBALS['dictionary'][$object], $file); include $file; // put the item in the sugar cache. $key = "VardefManager.{$module}.{$object}"; $data = $GLOBALS['dictionary'][$object]; sugar_cache_put($key, $data); }
/** * searchEngineDown * * This function creates a cache file to indicate search engine is down * */ function searchEngineDown() { $cacheDir = create_cache_directory('fts/'); sugar_touch($cacheDir . '/fts_down'); }
/** * returns a name for the XML File * * @param string $file_id - unique id to make part of the file name */ public static function getXMLFileName($file_id) { global $sugar_config, $current_user; $filename = $sugar_config['tmp_dir'] . $current_user->id . '_' . $file_id . '.xml'; if (!is_dir(dirname($filename))) { create_cache_directory(str_ireplace($GLOBALS['sugar_config']['cache_dir'], "", $filename)); } return $filename; }
/** * Get the list of available APIs * @param bool $forceRebuild * @param bool $ignoreDisabled Should we ignore disabled status? * @return array */ public static function loadFullAPIList($forceRebuild = false, $ignoreDisabled = false) { if (inDeveloperMode()) { static $beenHereBefore = false; if (!$beenHereBefore) { $forceRebuild = true; $beenHereBefore = true; } } $cached = sugar_cached('include/externalAPI.cache.php'); if (!$forceRebuild && file_exists($cached)) { // Already have a cache file built, no need to rebuild require $cached; return $ignoreDisabled ? $fullAPIList : self::filterAPIList($fullAPIList); } $apiFullList = array(); $meetingPasswordList = array(); $needUrlList = array(); $baseDirList = array('include/externalAPI/', 'custom/include/externalAPI/'); foreach ($baseDirList as $baseDir) { $dirList = glob($baseDir . '*', GLOB_ONLYDIR); foreach ($dirList as $dir) { if ($dir == $baseDir . '.' || $dir == $baseDir . '..' || $dir == $baseDir . 'Base') { continue; } $apiName = str_replace($baseDir, '', $dir); if (file_exists($dir . '/ExtAPI' . $apiName . '.php')) { $apiFullList[$apiName]['className'] = 'ExtAPI' . $apiName; $apiFullList[$apiName]['file'] = $dir . '/' . $apiFullList[$apiName]['className'] . '.php'; } if (file_exists($dir . '/ExtAPI' . $apiName . '_cstm.php')) { $apiFullList[$apiName]['className'] = 'ExtAPI' . $apiName . '_cstm'; $apiFullList[$apiName]['file_cstm'] = $dir . '/' . $apiFullList[$apiName]['className'] . '.php'; } } } $optionList = array('supportedModules', 'useAuth', 'requireAuth', 'supportMeetingPassword', 'docSearch', 'authMethod', 'oauthFixed', 'needsUrl', 'canInvite', 'sendsInvites', 'sharingOptions', 'connector', 'oauthParams', 'restrictUploadsByExtension'); foreach ($apiFullList as $apiName => $apiOpts) { require_once $apiOpts['file']; if (!empty($apiOpts['file_cstm'])) { require_once $apiOpts['file_cstm']; } $className = $apiOpts['className']; $apiClass = new $className(); foreach ($optionList as $opt) { if (isset($apiClass->{$opt})) { $apiFullList[$apiName][$opt] = $apiClass->{$opt}; } } // Special handling for the show/hide of the Meeting Password field, we need to create a dropdown for the Sugar Logic code. if (isset($apiClass->supportMeetingPassword) && $apiClass->supportMeetingPassword == true) { $meetingPasswordList[$apiName] = $apiName; } } create_cache_directory('/include/'); $cached_tmp = sugar_cached('include/externalAPI.cache-tmp.php'); $fd = fopen($cached_tmp, 'w'); fwrite($fd, "<" . "?php\n//This file is auto generated by " . basename(__FILE__) . "\n\$fullAPIList = " . var_export($apiFullList, true) . ";\n\n"); fclose($fd); rename($cached_tmp, $cached); $fd = fopen(sugar_cached('include/externalAPI.cache-tmp.js'), 'w'); fwrite($fd, "//This file is auto generated by " . basename(__FILE__) . "\nSUGAR.eapm = " . json_encode($apiFullList) . ";\n\n"); fclose($fd); rename(sugar_cached('include/externalAPI.cache-tmp.js'), sugar_cached('include/externalAPI.cache.js')); if (!isset($GLOBALS['app_list_strings']['extapi_meeting_password']) || is_array($GLOBALS['app_list_strings']['extapi_meeting_password']) && count(array_diff($meetingPasswordList, $GLOBALS['app_list_strings']['extapi_meeting_password'])) != 0) { // Our meeting password list is different... we need to do something about this. require_once 'modules/Administration/Common.php'; $languages = get_languages(); foreach ($languages as $lang => $langLabel) { $contents = return_custom_app_list_strings_file_contents($lang); $new_contents = replace_or_add_dropdown_type('extapi_meeting_password', $meetingPasswordList, $contents); save_custom_app_list_strings_contents($new_contents, $lang); } } return $ignoreDisabled ? $apiFullList : self::filterAPIList($apiFullList); }
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; }
/** * Save the dictionary object to the cache * @param string $module the name of the module * @param string $object the name of the object */ static function saveCache($module, $object, $additonal_objects = array()) { $file = create_cache_directory('modules/' . $module . '/' . $object . 'vardefs.php'); write_array_to_file('GLOBALS["dictionary"]["' . $object . '"]', $GLOBALS['dictionary'][$object], $file); if (sugar_is_file($file) && is_readable($file)) { include $file; } // put the item in the sugar cache. $key = "VardefManager.{$module}.{$object}"; //Sometimes bad definitions can get in from left over extensions or file system lag(caching). We need to clean those. $data = self::cleanVardefs($GLOBALS['dictionary'][$object]); sugar_cache_put($key, $data); }
/** * returns a name for the XML File * * @param string $file_id - unique id to make part of the file name */ public static function getXMLFileName($file_id) { create_cache_directory("xml/" . $GLOBALS['current_user']->getUserPrivGuid() . "_{$file_id}.xml"); return sugar_cached("xml/") . $GLOBALS['current_user']->getUserPrivGuid() . "_" . $file_id . ".xml"; }
function disc_client_file_sync($soapclient, $session, $verbose = false, $attempts = 0) { $max_attempts = 3; global $sugar_config; // files might be big ini_set("memory_limit", "-1"); $return_str = ""; $tempdir_parent = create_cache_directory("disc_client"); $temp_dir = tempnam($tempdir_parent, "sug"); sugar_mkdir($temp_dir, 0775); if (!is_dir($temp_dir)) { die("Could not create a temp dir."); } // get pattern file $result = $soapclient->call('get_encoded_file', array('session' => $session, 'filename' => "install/data/disc_client.php")); if (!empty($soapclient->error_str)) { if ($attempts < $max_attempts && substr_count($soapclient->error_str, 'HTTP Error: socket read of headers timed out') > 0) { echo "Could not retrieve file patterns list. Error was: " . $soapclient->error_str; $attempts++; echo "<BR> {$attempts} of {$max_attempts} attempts trying again<br>"; flush(); ob_flush(); return disc_client_file_sync($soapclient, $session, $verbose, $attempts); } die("Failed: Could not retrieve file patterns list. Error was: " . $soapclient->error_str); } if ($result['error']['number'] != 0) { die("Failed: Could not retrieve file patterns list. Error was: " . $result['error']['name'] . ' - ' . $result['description']); } $newfile = write_encoded_file($result, $temp_dir); if (!copy($newfile, $result['filename'])) { die("Could not copy {$newfile} to new location."); } // get array definitions: $disc_client_ignore require "install/data/disc_client.php"; // get file list/md5s, write as temp file, then require_once from tmp location $result = $soapclient->call('get_disc_client_file_list', array('session' => $session)); if (!empty($soapclient->error_str)) { if ($attempts < $max_attempts && substr_count($soapclient->error_str, 'HTTP Error: socket read of headers timed out') > 0) { echo "Could not retrieve file patterns list. Error was: " . $soapclient->error_str; $attempts++; echo "<BR> {$attempts} of {$max_attempts} attempts trying again<br>"; flush(); ob_flush(); return disc_client_file_sync($soapclient, $session, $verbose, $attempts); } die("Failed: Could not retrieve file list. Error was: " . $soapclient->error_str); } if ($result['error']['number'] != 0) { die("Failed: Could not retrieve file list. Error was: " . $result['error']['name'] . ' - ' . $result['description']); } $temp_file = tempnam($temp_dir, "sug"); write_encoded_file($result, $temp_dir, $temp_file); require_once $temp_file; // determine which files are needed locally $needed_file_list = array(); $server_files = array(); // used later for removing unneeded local files foreach ($server_file_list as $result) { $server_filename = $result['filename']; $server_md5 = $result['md5']; $server_files[] = $server_filename; $ignore = false; foreach ($disc_client_ignore as $ignore_pattern) { if (preg_match("#" . $ignore_pattern . "#", $server_filename)) { $ignore = true; } } if (file_exists($server_filename)) { if (!$ignore && md5_file($server_filename) != $server_md5) { // not on the ignore list and the client's md5sum does not match the server's $needed_file_list[] = $server_filename; } } else { if (!$ignore) { $return_str .= disc_client_utils_print("File missing from client : {$temp_dir}/{$server_filename}<br>", $verbose); $needed_file_list[] = $server_filename; } } } if (sizeof($server_files) < 100) { if ($attempts < $max_attempts && substr_count($soapclient->error_str, 'HTTP Error: socket read of headers timed out') > 0) { echo "Could not retrieve file patterns list. Error was: " . $soapclient->error_str; $attempts++; echo "<BR> {$attempts} of {$max_attempts} attempts trying again<br>"; flush(); ob_flush(); return disc_client_file_sync($soapclient, $session, $verbose, $attempts); } die("Failed: Empty file list returned from server. Please try again."); } // get needed files foreach ($needed_file_list as $needed_file) { $result = $soapclient->call('get_encoded_file', array('session' => $session, 'filename' => "{$needed_file}")); write_encoded_file($result, $temp_dir); } // all files recieved, copy them into place foreach ($needed_file_list as $needed_file) { if (file_exists("{$temp_dir}/{$needed_file}")) { mkdir_recursive(dirname($needed_file), true); copy("{$temp_dir}/{$needed_file}", $needed_file); $return_str .= disc_client_utils_print("Updated file: {$needed_file} <br>", $verbose); } else { $return_str .= disc_client_utils_print("File missing from client : {$temp_dir}/{$needed_file}<br>", $verbose); } } if (sizeof($needed_file_list) == 0) { $return_str .= disc_client_utils_print("No files needed to be synchronized.<br>", $verbose); } // scrub local files that are not part of client application $local_file_list = findAllFiles(".", array()); $removed_file_count = 0; foreach ($local_file_list as $local_file) { $ignore = false; foreach ($disc_client_ignore as $ignore_pattern) { if (preg_match("#" . $ignore_pattern . "#", $local_file)) { $ignore = true; } } if (!$ignore && !in_array($local_file, $server_files)) { // not on the ignore list and the server does not know about it unlink($local_file); $return_str .= disc_client_utils_print("Removed file: {$local_file} <br>", $verbose); $removed_file_count++; } } if ($removed_file_count == 0) { $return_str .= disc_client_utils_print("No files needed to be removed.<br>", $verbose); } return $return_str; }