Skip to content
Snippets Groups Projects
console.php 17.4 KiB
Newer Older
Prasad's avatar
Prasad committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
<?php
/*+**********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 ************************************************************************************/

chdir(dirname(__FILE__) . '/../..');
include_once 'vtlib/Vtiger/Module.php';
include_once 'vtlib/Vtiger/Package.php';
include_once 'includes/main/WebUI.php';

include_once 'include/Webservices/Utils.php';

class Vtiger_Tools_Console_Controller {
	const PROMPT_ANY      = 1;
	const PROMPT_OPTIONAL = 2;
	const PROMPT_NUMERIC  = 3;
	const PROMPT_ALPHANUMERIC = 4;
	const PROMPT_NAME     = 5;
	const PROMPT_LABEL    = 6;
	const PROMPT_PATH     = 7;
	
	protected $interactive = true;
	protected $arguments   = array();

	protected function __construct() { }
	
	public function setArguments($args, $interactive) {
		$this->arguments   = $args;
		$this->interactive = $interactive;
		return $this;
	}

	protected function handle() {
		global $argv;
		$this->arguments = $argv;
		
		// Discard the script name.
		array_shift($this->arguments);
		
		if ($this->arguments) {
			$this->arguments = explode('=', $this->arguments[0]);
			$this->interactive = false;
		}

		$this->welcome();
		$this->options();	
	}

	protected function welcome() {
		if ($this->interactive) {
			echo "Welcome to Vtiger CRM Creator.\n";
			echo "This tool will enable you to get started with developing extensions with ease.\n";
			echo "Have a good time. Press CTRL+C to \"quit\".\n";
		}
	}

	protected function options() {
		if ($this->interactive) {
			echo "Choose the options below:\n";
			echo "1. Create New Module.\n";
			echo "2. Create New Layout.\n";
			echo "3. Create New Language Pack.\n";
			echo "4. Create Test Language Pack.\n";
			echo "5. Import Module.\n";
			echo "6. Update Module.\n";
			echo "7. Remove Module.\n";
			$option = $this->prompt("Enter your choice: ", self::PROMPT_NUMERIC);
		} else {
			$option = array_shift($this->arguments);
			switch ($option) {
				case '--import': $option = 5; break;
				case '--update': $option = 6; break;
				case '--remove': $option = 7; break;
			}
		}

		try {
			switch (intval($option)) {
				case 1: $this->handleCreateModule(); break;
				case 2: $this->handleCreateLayout(); break;
				case 3: $this->handleCreateLanguage(); break;
				case 4: $this->handleCreateTestLanguage(); break;
				case 5: $this->handleImportModule(); break;
				case 6: $this->handleUpdateModule(); break;
				case 7: $this->handleRemoveModule(); break;
			}
		} catch (Exception $e) {
			echo "ERROR: " .$e->getMessage() . "\n";
			echo $e->getTraceAsString();
			echo "\n";
		}
	}

	protected function prompt($msg='', $type=self::PROMPT_ANY) {
		do {
			if ($msg) echo $msg;
			$value = trim(fgets(STDIN));

			if (!$value && $type == self::PROMPT_OPTIONAL) {
				return $value;

			} else if ($value) {

				switch ($type) {
					case self::PROMPT_NUMERIC:
						if (is_numeric($value)) {
							return $value;
						}
						break;
					case self::PROMPT_ALPHANUMERIC:
						if (!preg_match("/^[a-zA-Z0-9]+$/", $value)) {
							return $value;
						}
						break;
					case self::PROMPT_NAME:
						if (!preg_match("/^[a-zA-Z][^a-zA-Z0-9_ ]*$/", $value)) {
							return $value;
						}
						break;
					case self::PROMPT_LABEL:
						if (!preg_match("/^[a-zA-Z0-9_ ]+$/", $value)) {
							return $value;
						}
						break;
					case self::PROMPT_PATH:
						if (!preg_match("/^[a-zA-Z0-9_:+.-\/\\\\]+$/", $value)) {
							return $value;
						}
					default:
						return $value;
				}
			}
		} while (true);
	}

	protected function toAlphaNumeric($value) {
		return preg_replace("/[^a-zA-Z0-9_]/", "", $value);
	}

	protected function findFiles($dir, $file_pattern, &$files) {
		$items = glob($dir . '/*', GLOB_NOSORT);
		foreach ($items as $item) {
			if (is_file($item)) {
				if (!$file_pattern || preg_match("/$file_pattern/", $item)) {
					$files[] = $item;
				}
			} else if (is_dir($item) && ($dir != $item)) {
				$this->findFiles($item, $file_pattern, $files);
			}
		}
	}

	// Option Handlers
	protected function handleCreateModule() {
		$controller = new Vtiger_Tools_Console_ModuleController();
		$controller->setArguments($this->arguments, $this->interactive)->handle();
	}

	protected function handleCreateLanguage() {
		$controller = new Vtiger_Tools_Console_LanguageController();
		$controller->setArguments($this->arguments, $this->interactive)->handle();
	}

	protected function handleCreateTestLanguage() {
		$controller = new Vtiger_Tools_Console_TestLanguageController();
		$controller->setArguments($this->arguments, $this->interactive)->handle();
	}

	protected function handleCreateLayout() {
		$controller = new Vtiger_Tools_Console_LayoutController();
		$controller->setArguments($this->arguments, $this->interactive)->handle();
	}
	
	protected function handleImportModule() {
		$controller = new Vtiger_Tools_Console_ImportController();
		$controller->setArguments($this->arguments, $this->interactive)->handle();
	}
	
	protected function handleUpdateModule() {
		$controller = new Vtiger_Tools_Console_UpdateController();
		$controller->setArguments($this->arguments, $this->interactive)->handle();
	}
	
	protected function handleRemoveModule() {
		$controller = new Vtiger_Tools_Console_RemoveController();
		$controller->setArguments($this->arguments, $this->interactive)->handle();
	}

	// Static
	public static function run() {
		$singleton = new self();
		$singleton->handle();
	}
}

class Vtiger_Tools_Console_ModuleController extends Vtiger_Tools_Console_Controller {

	public function handle() {
		echo ">>> MODULE <<<\n";

		$moduleInformation = array();
		do {
			$moduleInformation['name'] = ucwords($this->prompt("Enter module name: ", self::PROMPT_NAME));
			$module = $this->find($moduleInformation['name']);
			if (!$module) {
				break;
			}
			echo "ERROR: " . $moduleInformation['name'] . " module already exists, try another.\n";
		} while (true);

		$moduleInformation['entityfieldlabel'] = 'Name';

		$entityfieldlabel = ucwords($this->prompt(sprintf("Entity field (%s): ",
				$moduleInformation['entityfieldlabel']), self::PROMPT_OPTIONAL));
		if ($entityfieldlabel) {
			$moduleInformation['entityfieldlabel'] = $entityfieldlabel;
		}

		$moduleInformation['parent'] = 'Tools';

		echo "Creating ...";
		$this->create($moduleInformation);
		echo "DONE.\n";
	}

	public function find($name) {
		return Vtiger_Module::getInstance($name);
	}

	protected function create($moduleInformation) {
		$moduleInformation['entityfieldname']  = strtolower($this->toAlphaNumeric($moduleInformation['entityfieldlabel']));

		$module = new Vtiger_Module();
		$module->name = $moduleInformation['name'];
		$module->parent=$moduleInformation['parent'];
		$module->save();

		$module->initTables();

		$block = new Vtiger_Block();
		$block->label = 'LBL_'. strtoupper($module->name) . '_INFORMATION';
		$module->addBlock($block);

		$blockcf = new Vtiger_Block();
		$blockcf->label = 'LBL_CUSTOM_INFORMATION';
		$module->addBlock($blockcf);

		$field1  = new Vtiger_Field();
		$field1->name = $moduleInformation['entityfieldname'];
		$field1->label= $moduleInformation['entityfieldlabel'];
		$field1->uitype= 2;
		$field1->column = $field1->name;
		$field1->columntype = 'VARCHAR(255)';
		$field1->typeofdata = 'V~M';
		$block->addField($field1);

		$module->setEntityIdentifier($field1);

		/** Common fields that should be in every module, linked to vtiger CRM core table */
		$field2 = new Vtiger_Field();
		$field2->name = 'assigned_user_id';
		$field2->label = 'Assigned To';
		$field2->table = 'vtiger_crmentity';
		$field2->column = 'smownerid';
		$field2->uitype = 53;
		$field2->typeofdata = 'V~M';
		$block->addField($field2);

		$field3 = new Vtiger_Field();
		$field3->name = 'createdtime';
		$field3->label= 'Created Time';
		$field3->table = 'vtiger_crmentity';
		$field3->column = 'createdtime';
		$field3->uitype = 70;
		$field3->typeofdata = 'T~O';
		$field3->displaytype= 2;
		$block->addField($field3);

		$field4 = new Vtiger_Field();
		$field4->name = 'modifiedtime';
		$field4->label= 'Modified Time';
		$field4->table = 'vtiger_crmentity';
		$field4->column = 'modifiedtime';
		$field4->uitype = 70;
		$field4->typeofdata = 'T~O';
		$field4->displaytype= 2;
		$block->addField($field4);

		// Create default custom filter (mandatory)
		$filter1 = new Vtiger_Filter();
		$filter1->name = 'All';
		$filter1->isdefault = true;
		$module->addFilter($filter1);
		// Add fields to the filter created
		$filter1->addField($field1)->addField($field2, 1)->addField($field3, 2);

		// Set sharing access of this module
		$module->setDefaultSharing();

		// Enable and Disable available tools
		$module->enableTools(Array('Import', 'Export', 'Merge'));

		// Initialize Webservice support
		$module->initWebservice();

		// Create files
		$this->createFiles($module, $field1);
	}

	protected function createFiles(Vtiger_Module $module, Vtiger_Field $entityField) {
		$targetpath = 'modules/' . $module->name;

		if (!is_file($targetpath)) {
			mkdir($targetpath);
			mkdir($targetpath . '/language');

			$templatepath = 'vtlib/ModuleDir/6.0.0';

			$moduleFileContents = file_get_contents($templatepath . '/ModuleName.php');
			$replacevars = array(
				'ModuleName'   => $module->name,
				'<modulename>' => strtolower($module->name),
				'<entityfieldlabel>' => $entityField->label,
				'<entitycolumn>' => $entityField->column,
				'<entityfieldname>' => $entityField->name,
			);

			foreach ($replacevars as $key => $value) {
				$moduleFileContents = str_replace($key, $value, $moduleFileContents);
			}
			file_put_contents($targetpath.'/'.$module->name.'.php', $moduleFileContents);
		}
	}

}

class Vtiger_Tools_Console_LayoutController extends Vtiger_Tools_Console_Controller {

	// Similar grouped patterns to identify the line on which tpl filename is specified.
	const VIEWERREGEX = '/\$viewer->(view|fetch)[^\(]*\(([^\)]+)/';
	const RETURNTPLREGEX = '/(return)([ ]+[\'"]+[^;]+)/';

	const TPLREGEX    = '/[\'"]([^\'"]+)/';

	public function handle() {
		echo ">>> LAYOUT <<<\n";

		$layoutInformation = array();
		do {
			$layoutInformation['name'] = strtolower($this->prompt("Enter layout name: ", self::PROMPT_NAME));
			if (!file_exists( 'layouts/' . $layoutInformation['name'])) {
				break;
			}
			echo "ERROR: " . $layoutInformation['name'] . " already exists, try another.\n";
		} while (true);

		echo "Creating ...";
		$this->create($layoutInformation);
		echo "DONE.\n";
	}

	protected function create($layoutInformation) {
		$files = array();
		$this->findFiles( 'includes', '.php$', $files);
		$this->findFiles( 'modules', '.php$', $files);

		$layoutdir =  'layouts/' . $layoutInformation['name'] . '/';

		foreach ($files as $file) {
			$tplfolder = $layoutdir . "modules/Vtiger";
			if (preg_match("/modules\/([^\/]+)\/([^\/]+)\//", $file, $fmatch)) {
				$tplfolder = $layoutdir . "modules/" . $fmatch[1];
				if ($fmatch[1] == 'Settings') {
					$tplfolder .= '/' . $fmatch[2];
				}
			}

			$tpls = array();
			$this->findTemplateNames($file, $tpls);
			$tpls = array_unique($tpls);

			if ($tpls) {
				foreach ($tpls as $tpl) {
					$tplname = basename($tpl, true);
					// Fix sub-directory path
					$tplpath = $tplfolder . '/'. substr($tpl, 0, strpos($tpl, $tplname));
					if (!file_exists($tplpath)) {
						mkdir($tplpath, 0755, true);
					}
					if (!file_exists($tplpath.$tplname)) {
						$initialContent = "{* License Text *}\n";
						// Enable debug to make it easy to implement.
						$initialContent.= "{debug}{* REMOVE THIS LINE AFTER IMPLEMENTATION *}\n\n";
						file_put_contents($tplpath.$tplname, $initialContent);
					}
					file_put_contents($tplpath.$tplname, "{* $file *}\n", FILE_APPEND);
				}
			}
		}
	}

	protected function findTemplateNames($file, &$tpls, $inreturn=false) {
		$contents = file_get_contents($file);

		$regex = $inreturn ? self::RETURNTPLREGEX : self::VIEWERREGEX;
		if (preg_match_all($regex, $contents, $matches)) {
			foreach ($matches[2] as $match) {
				if (preg_match(self::TPLREGEX, $match, $matches2)) {
					if (stripos($matches2[1], '.tpl') !== false) {
						$tpls[] = $matches2[1];
					}
				}
			}
			// Viewer files can also have return tpl calls - find them.
			if (!$inreturn) {
				$this->findTemplateNames($file, $tpls, true);
			}
		}
	}
}

class Vtiger_Tools_Console_LanguageController extends Vtiger_Tools_Console_Controller {

	const BASE_LANG_PREFIX = 'en_us';

	public function handle() {
		echo ">>> LANGUAGE <<<\n";

		$languageInformation = array();
		do {
			$languageInformation['prefix'] = strtolower($this->prompt("Enter (languagecode_countrycode): ", self::PROMPT_NAME));
			if (!file_exists( 'languages/' . $languageInformation['prefix'])) {
				break;
			}
			echo "ERROR: " . $languageInformation['prefix'] . " already exists, try another.\n";
		} while (true);

		echo "Creating ...";
		$this->create($languageInformation);
		echo "DONE.\n";
	}

	protected function create($languageInformation) {
		$files = array();
		$this->findFiles( 'languages/'.self::BASE_LANG_PREFIX, '.php$', $files);

		foreach ($files as $file) {
			$filename = basename($file, true);
			$dir = substr($file, 0, strpos($file, $filename));
			$dir = str_replace('languages/'.self::BASE_LANG_PREFIX, 'languages/'.$languageInformation['prefix'], $dir);
			if (!file_exists($dir)) mkdir($dir);

			if (isset($languageInformation['prefix_value'])) {
				$contents = file_get_contents($file);
				$contents = preg_replace("/(=>[^'\"]+['\"])(.*)/", sprintf('$1%s$2', $languageInformation['prefix_value']), $contents);
				file_put_contents($dir.'/'.$filename, $contents);
			} else {
				copy($file, $dir.'/'.$filename);
			}
		}
	}

	protected function deploy($languageInformation) {
		if (!isset($languageInformation['label'])) {
			echo "Language label not specified.";
			return;
		}

		$db = PearDatabase::getInstance();
		$check = $db->pquery('SELECT 1 FROM vtiger_language WHERE prefix=?', $languageInformation['prefix']);
		if ($check && $db->num_rows($check)) {
			;
		} else {
			$db->pquery('INSERT INTO vtiger_language (id,name,prefix,label,lastupdated,isdefault,active) VALUES(?,?,?,?,?,?,?)',
					array($db->getUniqueId('vtiger_language'), $languageInformation['label'], $languageInformation['prefix'],
							$languageInformation['label'], date('Y-m-d H:i:s'), 0, 1));
		}
	}
}

class Vtiger_Tools_Console_TestLanguageController extends Vtiger_Tools_Console_LanguageController {

	public function handle() {
		echo ">>> TEST LANGUAGE <<<\n";

		$languageInformation = array('label' => 'TEST', 'prefix' => 'te_st', 'prefix_value' => '✔ ');

		echo "Creating ...";
		$this->create($languageInformation);
		echo "DONE\n";

		echo "Deploying ...";
		$this->deploy($languageInformation);
		echo "DONE.\n";
	}
}

class Vtiger_Tools_Console_ImportController extends Vtiger_Tools_Console_Controller {
	
	public function handle() {
		if ($this->interactive) {
			echo ">>> IMPORT MODULE <<<\n";
			do {
				$path = $this->prompt("Enter package path: ", self::PROMPT_PATH);
				if (file_exists($path)) {
					break;
				}
				echo "ERROR: " . $path . " - file not found, try another.\n";
			} while (true);
		} else {
			$path = array_shift($this->arguments);
		}
		
		if (file_exists($path)) {
			$package = new Vtiger_Package();
			$module  = $package->getModuleNameFromZip($path);
			
			$moduleInstance = Vtiger_Module::getInstance($module);
			if ($moduleInstance) {
				echo "ERROR: Module $module already exists!\n";
			} else {
				echo "Importing ...";
				$package->import($path);
				echo "DONE.\n";
			}			
			
		} else {
			throw new Exception("Package file $path not found.");
		}
		
	}
}

class Vtiger_Tools_Console_UpdateController extends Vtiger_Tools_Console_Controller {
	
	public function handle() {
		if ($this->interactive) {
			echo ">>> UPDATE MODULE <<<\n";
			do {
				$path = $this->prompt("Enter package path: ", self::PROMPT_PATH);
				if (file_exists($path)) {
					break;
				}
				echo "ERROR: " . $path . " - file not found, try another.\n";
			} while (true);
		} else {
			$path = array_shift($this->arguments);
		}
		
		if (file_exists($path)) {
			$package = new Vtiger_Package();
			$module  = $package->getModuleNameFromZip($path);
			
			$moduleInstance = Vtiger_Module::getInstance($module);
			if (!$moduleInstance) {
				echo "ERROR: Module $module not found!\n";
			} else {
				echo "Updating ...";
				$package->update($moduleInstance, $path);
				echo "DONE.\n";
			}			
			
		} else {
			throw new Exception("Package file $path not found.");
		}
		
	}
}

class Vtiger_Tools_Console_RemoveController extends Vtiger_Tools_Console_Controller {
	
	public function handle() {
		if ($this->interactive) {
			echo ">>> REMOVE MODULE <<<\n";
			do {
				$module = $this->prompt("Enter module name: ", self::PROMPT_NAME);
				$moduleInstance = Vtiger_Module::getInstance($module);
				if (!$moduleInstance) {
					echo "ERROR: Module $module not found, try another.\n";
				} else {
					echo "Removing ...";
					$moduleInstance->delete();
					echo "DONE.\n";
				}
			} while (true);
		} else {
			$module = array_shift($this->arguments);
			$moduleInstance = Vtiger_Module::getInstance($module);
			if (!$moduleInstance) {
				echo "ERROR: Module $module not found!\n";
			} else {
				echo "Removing ...";
				$moduleInstance->delete();
				echo "DONE.\n";
			}			
		}
	}
}

if (php_sapi_name() == 'cli') {
	Vtiger_Tools_Console_Controller::run();
} else {
	echo "Usage: php -f vtlib/tools/creator.php";
}