/*
Разбирает XML файл со структурой таблиц

@param string $module имя модуля
@return array список таблиц
183500
public function parseSchema($module) {
        
      if (!isset($this->schemas[$module])) return false;
      if (!isset($this->schemas[$module]['schema'])) return false;
      
      $file = $this->schemas[$module]['schema'];
      
    	if (!file_exists($file) || !is_file($file)) throw new Exception\CMS(Exception\CMS::FILE_NOT_FOUND, $file);
    
    	$data = implode("",file($file));
    	$parser = xml_parser_create();
    	xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
    	xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
    	xml_parse_into_struct($parser,$data,$values,$tags);
    	xml_parser_free($parser);
    	
    	$res = [
          'tables'  => [],
          'types'   => [],
          'widgets' => [],
		  'menus'   => [],
        ];
      
    	foreach ($values as $value) {
			
    		if ($value['tag'] == 'menu') {
    		    if ($value['type'] == 'open') {
					$value['attributes']['data'] = [];
					$res['menus'][] = $value['attributes'];
				}
    		}	
			if ($value['tag'] == 'menuitem') {
				if ($value['type'] != 'close') {
					$res['menus'][count($res['menus'])-1]['data'][] = $value['attributes'];
				}
			}
      
    		if ($value['tag'] == 'table') {
    		    if ($value['type'] == 'open') $table = $value['attributes'];
    		    if ($value['type'] == 'close') {
                    if (isset($table['engine']) && $table['engine'] == 'HEAP') $table['engine'] = 'MEMORY';
                    $res['tables'][$table['name']] = $table;
                }
    		}
        
    		if ($value['tag'] == 'widgetcontainer') {
    		    if ($value['type'] == 'open') {
                $widget = $value['attributes'];
                $widget['widgets'] = array();
            }
    		    if ($value['type'] == 'close') $res['widgets'][$widget['widgetAlias']] = $widget;
    		}
        
			if ($value['tag'] == 'widget') {
				$value['attributes']['params'] = trim($value['value']);
				$widget['widgets'][] = $value['attributes'];
			}  
        
    		if ($value['tag'] == 'object') {
    		    if ($value['type'] == 'open') $table = $value['attributes'];
    		    if ($value['type'] == 'close') $res['types'][$table['name']] = $table;
    		}        
        
    		if ($value['tag'] == 'field' && isset($value['attributes']['name'])) {
    			if (!isset($table['fields'])) $table['fields'] = array();
    			$table['fields'][$value['attributes']['name']] = $value['attributes'];
    		}
        
    		if ($value['tag'] == 'key') {
    		    if ($value['type'] == 'open') $key = $value['attributes'];
    			if ($value['type'] == 'close') {
					if ($key['name']) {
						if (!isset($table['keys'])) $table['keys'] = array();	
						$table['keys'][$key['name']] = $key;
					}
    			}
    		}
        
    		if ($value['tag'] == 'column' && isset($value['attributes']['name'])) {
    			if (!isset($key['columns'])) $key['columns'] = array();
    			$key['columns'][] = $value['attributes'];
    		}
        
    	}
		
		if ($module == 'core') {
			try {
				foreach (ObjectDefinition::enum() as $od) {
					foreach ($od->getFields() as $f) {
						
						if (is_a($f, '\\Cetera\\ObjectFieldLinkSet2')) {
							
							$res['tables'][$f->getLinkTable()] = [
								'name'   => $f->getLinkTable(),
								'fields' => [
									'id' => [
										'name' => 'id',
										'type' => 'int(11)',
										'null' => 0
									],
									'dest_type' => [
										'name' => 'dest_type',
										'type' => 'int(11)',
										'null' => 0
									],
									'dest_id' => [
										'name' => 'dest_id',
										'type' => 'int(11)',
										'null' => 0
									],
									'tag' => [
										'name' => 'tag',
										'type' => 'int(11)',
										'default' => 0,
										'null' => 0
									],
								],
								'keys' => [
									'PRIMARY' => [
										'name' => 'PRIMARY',
										'unique' => 1,
										'columns' => [
											['name' => 'id'],
											['name' => 'dest_type'],
											['name' => 'dest_id'],
										]
									],
									'dest' => [
										'name' => 'dest',
										'unique' => 0,
										'columns' => [
											['name' => 'dest_type'],
											['name' => 'dest_id'],
										]
									],
								]
							];
							
						}						
						
						if (is_subclass_of($f, '\\Cetera\\ObjectFieldLinkSetAbstract')) {
							
							$res['tables'][$f->getLinkTable()] = [
								'name'   => $f->getLinkTable(),
								'fields' => [
									'id' => [
										'name' => 'id',
										'type' => 'int(11)',
										'null' => 0
									],
									'dest' => [
										'name' => 'dest',
										'type' => 'int(11)',
										'null' => 0
									],
									'tag' => [
										'name' => 'tag',
										'type' => 'int(11)',
										'default' => 0,
										'null' => 0
									],
								],
								'keys' => [
									'PRIMARY' => [
										'name' => 'PRIMARY',
										'unique' => 1,
										'columns' => [
											['name' => 'id'],
											['name' => 'dest'],
										]
									],
									'dest' => [
										'name' => 'dest',
										'unique' => 0,
										'columns' => [
											['name' => 'dest'],
										]
									],
								]
							];
							
						}
					}
				}
			}
			catch (\Exception $e) {}
			
		}		
      
    	return $res;
    }
334430
public static function requireModule($module)
    {
        // Check for module itself
        $file_path = DIR_MODULES . $module . '/' . 'Module' . Converter::toCamelCase($module) . '.php';
        if (file_exists($file_path)) {
            require_once $file_path;

            // Inner panel file
            if (MODE == 'cms') {
                $file_path = DIR_MODULES . $module . '/' . 'Cms' . ucfirst($module) . '.php';
                if (file_exists($file_path)) {
                    require_once $file_path;
                }
            }
        }

        // Require all Entity files
        $objects_path = DIR_MODULES . $module . '/Entity/';
        if (file_exists($objects_path)) {
            foreach (array_diff(scandir($objects_path), ['.', '..']) as $object_file) {
                if (is_file($objects_path . $object_file)) {
                    require_once $objects_path . $object_file;
                }
            }
        }
    }
971404
protected function getModuleConfig(string $module, array $options = []): ModuleConfig
    {
        $configFile = empty($options['configFile']) ? null : $options['configFile'];
        $mc = new ModuleConfig(ConfigType::MIGRATION(), $module, $configFile, ['cacheSkip' => true]);

        $schema = $mc->createSchema(['lint' => true]);
        $mc->setParser(new Parser($schema, ['lint' => true, 'validate' => true]));

        return $mc;
    }
862474
public function add_module($title) {
        $this->resource_count++;
        $resource_str = str_pad($this->resource_count.'',6,'0',STR_PAD_LEFT);
        $identifier = 'T_'.$resource_str;

        $xpath = new \DOMXpath($this);

        $items = $xpath->query(CC::item_xpath)->item(0);
        $module = $this->add_child_ns(CC::CC_1_1_CP, $items, 'item', null, array('identifier' => $identifier));
        $new_title = $this->add_child_ns(CC::CC_1_1_CP, $module, 'title', $title);
        return $module;
    }
173381
public static function getModuleInfo($module=null, $parent=null)
	{
		define('DS', DIRECTORY_SEPARATOR);
		if($module != null) {
			$modulePath = Yii::getPathOfAlias('application.modules.'.$module);
			$moduleFile = $module.'.yaml';
			if($parent != null) {
				$modulePath = Yii::getPathOfAlias('application.modules.'.$parent);
				$module = $parent.'-'.$module;
				$moduleFile = $module.'.yaml';
			}
			$YMLPath = $modulePath.'/'.$moduleFile;

			if(!file_exists($YMLPath)) {
				$modulePath = Yii::getPathOfAlias('ommu.'.$module);
				if($parent != null) {
					$modulePath = Yii::getPathOfAlias('ommu.'.$parent);
				}
				$YMLPath = $modulePath.'/'.$moduleFile;
			}
			
		} else
			$YMLPath = Yii::getPathOfAlias('application.libraries.core').DS.'core.yaml';
			
		if(file_exists($YMLPath)) {
			$moduleInfo = self::getArrayFromYML($YMLPath);
			
			return $moduleInfo;
			
		} else
			return false;
	}
1367899
private static function copyDeltasFromPackage($module)
    {
        $docRoot = self::docRoot();
        $melisVendorPath = $docRoot . 'vendor/melisplatform/' . $module;
        $dbDeployPath = $docRoot . 'dbdeploy/data/';
        if (!file_exists($melisVendorPath)) {
            return;
        }
        if (!file_exists($dbDeployPath)) {
            mkdir($dbDeployPath, 0777, true);
        }
        // copy dbdeploy file
        $packageDbdeployFiles = $melisVendorPath . '/install/dbdeploy/';
        if (!file_exists($packageDbdeployFiles)) {
            return null;
        }
        $packageDbdeployFiles = glob($packageDbdeployFiles . '*.sql');
        $moduleName = self::toModuleName($module);

        print  "* $moduleName\r\n";
        $count = 1;
        $allExists = false;
        foreach ($packageDbdeployFiles as $idx => $file) {
            if (!file_exists($dbDeployPath . basename($file))) {
                $count = $idx + 1;
                print "    ($count) " . 'Publishing ' . $moduleName . '/' . basename($file) . ' => ' . $dbDeployPath . basename($file) . PHP_EOL;
                copy($file, $dbDeployPath . basename($file));
                self::$count++;
                $allExists = false;
            } else {
                $allExists = true;
            }

        }

        if ($allExists) {
            print  "    Nothing to publish" . PHP_EOL;
        }

        print PHP_EOL;
    }
172239
public function getModuleCustomTable($module)
    {
        $sugarBean = $this->getBean($module);
        $customTable = $sugarBean->get_custom_table_name();
        $data = $this->db->query("SHOW TABLES LIKE '$customTable'");
        if (empty($data)) {
            return '';
        }

        return $customTable;
    }
966001
public function canonical($module)
	{
		$module = preg_replace('/[^A-Z0-9_\.-]/i', '', $module);
		if (substr($module, 0, strlen('mod_')) != 'mod_')
		{
			$module = 'mod_' . $module;
		}
		return $module;
	}
987845
protected function getModuleInformation(Repository $repository, $module)
    {
        return [
            '#'           => $module['order'],
            'location'    => $repository->location,
            'name'        => isset($module['name']) ? $module['name'] : '',
            'slug'        => $module['slug'],
            'description' => isset($module['description']) ? $module['description'] : '',
            'status'      => (modules($repository->location)->isEnabled($module['slug'])) ? 'Enabled' : 'Disabled',
        ];
    }
1174706
public static function getModuleAlias($module) {
        if (NULL !== $alias = static::getConfig('modules', $module, 'alias', false)) {
            return $alias;
        }

        return Util::camelToHyphen($module);
    }
236185
public function getModuleNames(AbstractNode $node): array
    {
        $docBlock = $this->getDocBlock($node);

        if ($docBlock === null) {
            return [];
        }

        $moduleTags = $docBlock->getTagsByName(static::TAG_MODULE);
        $moduleTags = $this->docBlockMapper->tagsToArray($moduleTags);

        return $moduleTags[static::TAG_MODULE] ?? [];
    }
187194
public function getSubmodules($module)
    {
        $submodsConfig = static::submodsConfig();
        $result = [];
        foreach ($submodsConfig as $submodUniqueId => $config) {
            if (($pos = strrpos($submodUniqueId, '/')) !== false) {
                $parentUid = substr($submodUniqueId, 0, $pos);
                $moduleId = substr($submodUniqueId, $pos + 1);
            } else {
                $parentUid = ''; // Yii::$app
                $moduleId = $submodUniqueId;
            }
            if ($parentUid == $module->uniqueId) {
                $result[$moduleId] = $config;
            }
        }
        return $result;
    }
1011406
public function removeModule($module)
    {
        foreach ($this->modules as $key => $moduleElement) {
            if ($moduleElement === $module) {
                unset($this->modules[$key]);
                break;
            }
        }

        return $this;
    }
98437
public static function loadScriptingModule($module)
    {
        $fullScriptPath = false;

        //  Remove any quotes from this passed in module
        $module = trim(str_replace(["'", '"'], null, $module), ' /');

        //  Check the configured script paths
        if (null === ($script = array_get(static::$libraries, $module))) {
            $script = $module;
        }

        foreach (static::$libraryPaths as $key => $path) {
            $checkScriptPath = $path . DIRECTORY_SEPARATOR . $script;

            if (is_file($checkScriptPath) && is_readable($checkScriptPath)) {
                $fullScriptPath = $checkScriptPath;
                break;
            }
        }

        if (!$script || !$fullScriptPath) {
            throw new InternalServerErrorException(
                'The module "' . $module . '" could not be found in any known locations.'
            );
        }

        return file_get_contents($fullScriptPath);
    }
114622
public function bindModuleUrl($modulename, $xsl="", $lang="")
	{
		$queryStart = strpos($modulename, "?");
		$queryString = "";

		if ($queryStart!==false)
		{
			$queryString = "&" . substr($modulename, $queryStart+1);
			$modulename = substr($modulename, 0, $queryStart);
		}

		if (strpos($modulename, "module:") !== false)
		{
			$modulename = substr($modulename, 7);
		}

		if(empty($xsl))
		{
			if ($this->getXsl()=="index")
			{
				$xsl = 	$this->get("xmlnuke.DEFAULTPAGE");

			}
			else
			{
				$xsl = $this->getXsl();
			}
		}

		if(empty($lang))
			$lang = strtolower($this->Language()->getName());


		$fullLink = $this->get("xmlnuke.USEFULLPARAMETER");
		if (!$fullLink)
		{
			if ($xsl == $this->get("xmlnuke.DEFAULTPAGE"))
			{
				$xsl = "";
			}
			$array = array_keys($this->LanguagesAvailable());
			if ($lang == $array[0])
			{
				$lang = "";
			}
		}

		$url = $this->UrlModule()."?module=".$modulename;
		$url .= $queryString;
		if ($xsl != "")
		{
			$url .= "&xsl=".$xsl;
		}
		if ($lang != "")
		{
			$url .= "&lang=".$lang;
		}

		return $url;
	}
1126426
protected function getModuleConfig(string $module, array $options = []): ModuleConfig
    {
        $mc = new ModuleConfig(ConfigType::MODULE(), $module, null, ['cacheSkip' => true]);
        $schema = $mc->createSchema(['lint' => true]);
        $schema->setCallback(function (array $schema) use ($module, $options) {
            // phpstan
            $displayBad = !empty($options['display_field_bad_values'])? (array)$options['display_field_bad_values'] : [];
            $iconBad = !empty($options['icon_bad_values'])? (array)$options['icon_bad_values'] : [];

            $schema = $this->addFieldsToSchema($schema, $module);
            $schema = $this->addVirtualFieldsToSchema($schema, $module);
            $schema = $this->addModulesToSchema($schema, $module);
            $schema = $this->addConversionToSchema($schema);
            $schema = $this->addDisplayFieldValidationToSchema($schema, $displayBad);
            $schema = $this->addIconValidationToSchema($schema, $iconBad);

            return $schema;
        });

        $mc->setParser(new Parser($schema, ['lint' => true, 'validate' => true]));

        return $mc;
    }
249972
public static function getPosts($module)
    {
        $fields = json_decode(json_encode(get_fields($module->ID)));
        if ($fields->posts_data_source == 'input') {
            return self::getManualInputPosts($fields->data);
        }

        return get_posts(self::getPostArgs($module->ID));
    }