phpeace.php 29.6 KB
Newer Older
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
1 2 3 4 5 6
<?php
/********************************************************************
  
   PhPeace - Portal Management System

   Copyright notice
7
   (C) 2003-2019 Francesco Iannuzzelli <[email protected]>
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
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
   All rights reserved

   This script is part of PhPeace.
   PhPeace is free software; you can redistribute it and/or modify 
   it under the terms of the GNU General Public License as 
   published by the Free Software Foundation; either version 2 of 
   the License, or (at your option) any later version.

   PhPeace 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 General Public License for more details.

   The GNU General Public License (GPL) is available at
   http://www.gnu.org/copyleft/gpl.html.
   A copy can be found in the file COPYING distributed with 
   these scripts.

   This copyright notice MUST APPEAR in all copies of the script!

********************************************************************/

include_once(SERVER_ROOT."/../classes/db.php");
include_once(SERVER_ROOT."/../classes/file.php");
include_once(SERVER_ROOT."/../classes/ini.php");

/**
 * Minimum size of a PhPeace update package (in KB)
 *
 */
define('MIN_PHPEACE_UPDATE_SIZE_KB',800);

/* #####################################
   PhPeace build, version and DB version numbers.
   To be manually updated whenever a new version is started
   or there's a change to the DB schema */

/**
 * PhPeace build number (integer)
 * Increased by 1 for each new build
 */
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
49
define('PHPEACE_BUILD',303);
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
50 51 52 53

/**
 * PhPeace version number (string)
 * Follows this convention:
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
54
 * [Major version number].[Minor version number].[Release number]
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
55
 */
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
56
define('PHPEACE_VERSION',"2.6.24");
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
57 58 59 60 61

/**
 * PhPeace Database version number (integer)
 * Increased by 1 for each DB schema change
 */
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
62
define('PHPEACE_DB_VERSION',269);
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
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

/* ##################################### */


/**
 * Core class to manage PhPeace instance.
 * It is also used for managing the relationship between the 
 * local installation and the main server one, from where modules
 * configuration and software updates are distributed
 *
 * @package PhPeace
 * @author Francesco Iannuzzelli <[email protected]>
 */
class PhPeace
{
	/**
	 * Whether this is a PhPeace main node
	 * (i.e. providing updates to other PhPeace instances)
	 *
	 * @var boolean
	 */
	public $main;

	/**
	 * PhPeace main node for this instance (URL)
	 *
	 * @var string
	 */
	public $phpeace_server;

	/**
	 * Current PhPeace version
	 *
	 * @var string
	 */
	public $version;

	/**
	 * Current build number
	 *
	 * @var integer
	 */
	public $build;

	/**
	 * Whether this PhPeace instance has been registered with a main node
	 *
	 * @var boolean
	 */
	public $registered;

	/**
	 * Current Database version
	 *
	 * @var integer
	 */
	public $db_version;

	/**
	 * Temporary path for updates
	 *
	 * @var string
	 */
	private $tpath;
	
	/** 
	 * @var Ini */
	private $ini;

	/**
	 * Constructor initialises public paths and internal variables
	 *
	 */
	function __construct()
	{
		$this->ini = new Ini;
		$this->main = $this->ini->Get('main');
		$this->phpeace_server = $this->ini->Get('phpeace_server');
		$this->title = $this->ini->Get('title');
		$this->registered = $this->ini->Get("registered");		
		$this->tpath = "temp";
		$this->build = PHPEACE_BUILD;
		$this->version = PHPEACE_VERSION;
		$this->db_version = PHPEACE_DB_VERSION;
	}
	
	/**
	 * Whether the current user is administrator of PhPeace module
	 *
	 * @return boolean
	 */
	public function AmIAdmin()
	{
		include_once(SERVER_ROOT."/../classes/session.php");
		$session = new Session();
		$id_user = ($session->Get("real_user_id")>0)? $session->Get("real_user_id") : $session->Get("current_user_id");
		$admin = FALSE;
		if ($session->Get('current_user_id')>0)
		{
			$db =& Db::globaldb();
			$db->query_single( $admin, "SELECT id_user FROM module_users WHERE id_user='$id_user' AND is_admin=1 AND id_module=17");
			if ($admin['id_user']>0)
				$admin = TRUE;
		}
		return $admin;
	}

	/**
	 * Block/Release access to admin interface for all but Phpeace module administrators
	 * Useful for maintenance needs
	 * (it's automatically called during version updates)
	 *
	 * @param integer $at_work
	 *   1 for true, 0 for false
	 */
	public function AtWork($at_work)
	{
		$this->ini->Set("at_work",$at_work);
	}

	/**
	 * Notify PhPeace admins of a defect
	 *
	 * @param integer $id_user ID of submitter
	 * @param integer $id_module ID of the last module used by submitter
	 * @param string $description Error description
	 */
	public function BugNotify( $id_user,$id_module,$description )
	{
		include_once(SERVER_ROOT."/../classes/adminhelper.php");
		include_once(SERVER_ROOT."/../classes/user.php");
		$ah = new AdminHelper;
		$u = new User();
		$u->id = $id_user;
		$row = Modules::ModuleGet($id_module);
		$row2 = $u->UserGet();
		$message = "User: {$row2['name']} (" . $ah->session->Get('current_user_login') . ")\n";
		$message .= "Module: {$row['path']}\n";
		$message .= "Version: {$this->version}\n";
		$message .= "Build: {$this->build}\n\n";
		$message .= $description . "\n\n";
		include_once(SERVER_ROOT."/../classes/translator.php");
		$tr = new Translator(0,0);
		$footer = $tr->TranslateParams("bug_notes",array($this->ini->Get('title'))) . "\n\n";
		$th = new TextHelper();
		$th->TextClean($footer);
		$message .= $footer;
		$ah->WarnAdmin("Defect Notification",$message,false);
		$ah->MessageSet("thanks_defect");
	}

	/**
	 * Verify if a PhPeace client is registered on this site
	 *
	 * @param string $install_key
	 * @return array
	 */
	public function ClientCheck($install_key)
	{
		$row = array();
		$db =& Db::globaldb();
		$sqlstr = "SELECT id_client,name,approved FROM clients WHERE install_key='$install_key'";
		$db->query_single($row, $sqlstr);
		return $row;
	}

	/**
	 * Remove a PhPeace client from this site
	 *
	 * @param integer $id_client
	 */
	public function ClientDelete( $id_client )
	{
		$db =& Db::globaldb();
		$sqlstr = "DELETE FROM clients WHERE id_client='$id_client'";
		$db->begin();
		$db->lock( "clients" );
		$res[] = $db->query( $sqlstr );
		Db::finish( $res, $db);
	}

	/**
	 * Retrieve a PhPeace client from this site
	 *
	 * @param integer $id_client
	 * @return array
	 */
	public function ClientGet($id_client)
	{
		$row = array();
		$db =& Db::globaldb();
		$sqlstr = "SELECT id_client,name,contact,email,install_key,latest_version,
		UNIX_TIMESTAMP(last_contact) AS last_contact_ts,approved,admin_web,modules,modules_update,php_version
		FROM clients WHERE id_client='$id_client'";
		$db->query_single($row, $sqlstr);
		return $row;
	}
	
	/**
	 * Retrieve the ID of active modules of a specific client
	 *
	 * @param integer $id_client
	 * @return array
	 */
	public function ClientModulesIDs($id_client)
	{
		$client = $this->ClientGet($id_client);
		include_once(SERVER_ROOT."/../classes/varia.php");
		$v = new Varia();
		$client_modules = $v->Deserialize($client['modules'],false);
		$client_modules_ids = array();
		if(is_array($client_modules) && count($client_modules)>0)
		{
			foreach($client_modules as $client_module)
			{
				if($client_module['active'])
					$client_modules_ids[] = $client_module['id_module'];
			}
		}
		return $client_modules_ids;
	}
	
	/**
	 * Update the modules associated to a PhPeace client and set its 
	 * module_update flag to trigger an update on next connection
	 *
	 * @param integer $id_client
	 * @param array $modules
	 */
	public function ClientModulesUpdate( $id_client, $modules )
	{
		if (is_array($modules))
		{
			include_once(SERVER_ROOT."/../classes/varia.php");
			$v = new Varia();
			$smodules = $v->Serialize($modules,true,false);
			$db =& Db::globaldb();
			$sqlstr = "UPDATE clients SET modules='$smodules',modules_update='1' WHERE id_client='$id_client' ";
			$db->begin();
			$db->lock( "clients" );
			$res[] = $db->query( $sqlstr );
			Db::finish( $res, $db);
		}
	}
	
	/**
	 * Set the update flag for a client,
	 * to mark that a change has happened in its modules configuration
	 *
	 * @param boolint $value		0=no change, 1=change
	 * @param integer $id_client
	 */
	private function ClientModulesUpdateSet($value,$id_client)
	{
		$db =& Db::globaldb();
		$sqlstr = "UPDATE clients SET modules_update='$value' WHERE id_client='$id_client' ";
		$db->begin();
		$db->lock( "clients" );
		$res[] = $db->query( $sqlstr );
		Db::finish( $res, $db);
	}
	
	/**
	 * Update PhPeace client info
	 *
	 * @param integer $id_client ID
	 * @param string $name Name of installation
	 * @param string $contact Name of mantainer
	 * @param string $email Email of mantainer
	 * @param integer $approved Approved
	 *   1 for true, 0 for false
	 */
	public function ClientUpdate( $id_client, $name, $contact, $email, $approved )
	{
		$db =& Db::globaldb();
		$sqlstr = "UPDATE clients SET name='$name',contact='$contact',email='$email',approved=$approved
		WHERE id_client='$id_client'";
		$db->begin();
		$db->lock( "clients" );
		$res[] = $db->query( $sqlstr );
		Db::finish( $res, $db);
	}
	
	/**
	 * Update PhPeace client information
	 * Called by the client itself during night updates
	 *
	 * @param string $install_key Key
	 * @param string $admin_web Admin URL
	 * @param string $php_version PHp version
	 * @param array $modules Modules configuration
	 * @return string Serialized modules configuration
	 */
	public function ClientUpdateRemote($install_key,$admin_web,$php_version,$modules)
	{
		include_once(SERVER_ROOT."/../classes/varia.php");
		$v = new Varia();
		$client = $this->ClientCheck($install_key);
		if ($client['id_client']>0)
		{
			$crow = $this->ClientGet($client['id_client']);
			$sqlstr = "UPDATE clients SET admin_web='$admin_web',php_version='$php_version',"; 
			$cmodules = $v->Deserialize($crow['modules'],false);
			if(!is_array($cmodules) || (is_array($cmodules) && count($cmodules)==0))
				$sqlstr .= "modules='$modules',";
			$db =& Db::globaldb();
			$sqlstr .= "last_contact='" . $db->GetTodayTime() . "' WHERE id_client='{$client['id_client']}'";
			$db->begin();
			$db->lock( "clients" );
			$res[] = $db->query( $sqlstr );
			Db::finish( $res, $db);
			$rmodules = array();
			if($crow['modules_update']=="1")
			{
				if (is_array($cmodules) && count($cmodules)>0)
				{
					$rmodules = $cmodules;
					$this->ClientModulesUpdateSet(0,$client['id_client']);
				}
			}
		}
		return $v->Serialize($rmodules,false,false);
	}

	/**
	 * Update PhPeace client based on its last connection to this site
	 *
	 * @param integer $id_client ID
	 * @param integer $build Build number
	 */
	public function ClientUpdateLast( $id_client, $build )
	{
		$db =& Db::globaldb();
		$sqlstr = "UPDATE clients SET last_contact='" . $db->GetTodayTime() . "' ";
		if($build>0)
			$sqlstr .= ",latest_version=$build";
		$sqlstr .= " WHERE id_client='$id_client' ";
		$db->begin();
		$db->lock( "clients" );
		$res[] = $db->query( $sqlstr );
		Db::finish( $res, $db);
	}

	/**
	 * Clients of this site (paginated)
	 *
	 * @param array $rows
	 * @return integer Num of clients
	 */
	public function Clients( &$rows )
	{
		$db =& Db::globaldb();
		$rows = array();
		$sqlstr = "SELECT c.id_client,c.name,c.contact,c.email,c.latest_version,
		UNIX_TIMESTAMP(last_contact) AS last_contact_ts,c.approved,admin_web
			FROM clients c 
			ORDER BY c.last_contact DESC";
		return $db->QueryExe($rows, $sqlstr, true);
	}

	/**
	 * Update PhPeace module configuration
	 *
	 * @param integer $debug_mail Debug mail messages to a text file
	 *   1 for true, 0 for false
	 * @param string $mail_output File name for mail debug
	 * @param string $phpeace_server URL of Phpeace server for updates
	 * @param date $install_date Installation date
	 */
	public function ConfigurationUpdate($debug_mail,$mail_output,$phpeace_server,$install_date)
	{
		$this->ini->Set("install_date",$install_date);
		$this->ini->Set("debug_mail",$debug_mail);
		$this->ini->Set("mail_output",$mail_output);
		$this->ini->Set("phpeace_server",$phpeace_server);
		if ($debug_mail=="0")	
		{
			$fm = new FileManager;
			$fm->Delete($mail_output);
		}
	}

	/**
	 * Copyright information
	 *
	 * @return string
	 */
	public function Copyright()
	{
452
		return "PhPeace $this->version (build $this->build) - Copyright &copy; 2019 Francesco Iannuzzelli";
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
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 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
	}

	/**
	 * Retrieve CSS for Admin interface
	 *
	 * @return string
	 */
	public function CssGet()
	{
		$fm = new FileManager;
		$css = $fm->TextFileRead("admin/include/css/custom.css");
		$css = str_replace("<style type=\"text/css\"><!--","",$css);
		$css = str_replace("--></style>","",$css);
		return trim($css);
	}
	
	/**
	 * Store CSS for Admin interface
	 *
	 * @param string $css
	 */
	public function CssStore($css)
	{
		$fm = new FileManager;
		$fm->WritePage("admin/include/css/custom.css",$css);
	}
	
	/**
	 * Update favicon
	 *
	 * @param array $file Uploaded file
	 */
	public function FaviconUpdate( $file )
	{
		if (count($file)>0)
		{
			$fm = new FileManager;
			$fm->MoveUpload($file['temp'],"uploads/custom/favicon.ico");
			$fm->Copy("uploads/custom/favicon.ico","admin/favicon.ico");
			$fm->PostUpdate();
		}
	}

	/**
	 * Build file name of update package based on build number
	 *
	 * @param integer $id_version
	 * @return string
	 */
	public function FileNameUpdate($id_version)
	{
		return "update_" . sprintf("%03d",$id_version);
	}
	
	/**
	 * Extract build number from the filename of an update package
	 *
	 * @param string $filename
	 * @return integer
	 */
	public function FileName2VersionId($filename)
	{
		$id_version = str_replace("update_","",$filename);
		$id_version = str_replace(".gz","",$id_version);
		$id_version = str_replace(".tar","",$id_version);
		$id_version = ltrim($id_version,'0');
		return $id_version;
	}

	/**
	 * Check wether this PhPeace has already registered with its PhPeace server
	 *
	 * @return boolean
	 */
	public function IsRegistered()
	{
        if (empty($this->phpeace_server))
            return false;
		$url = "$this->phpeace_server/phpeace/registered.php?k=" . $this->ini->Get("install_key");
		$fm = new FileManager;
		return ($fm->Browse($url)=="1")? true:false;
	}

	/**
	 * Validate an installation key
	 *
	 * @param string $install_key
	 * @return boolean
	 */
	public function KeyCheck($install_key)
	{
		return (strlen($install_key)==32);
	}
	
	/**
	 * Languages supported by the portal
	 *
	 * @param integer $id_language
	 * @return array
	 */
	public function Languages($id_language=0)
	{
		include_once(SERVER_ROOT."/../classes/translator.php");
		$tr = new Translator($id_language,0);
		$languages = $tr->Translate("languages");
		unset($languages['5']);
		unset($languages['8']);
		unset($languages['9']);
		unset($languages['14']);
		unset($languages['15']);
		unset($languages['16']);
		unset($languages['17']);
		$languages[0] = "___";
		reset($languages);
		return $languages;
	}

	/**
	 * Update logo for admin interface
	 *
	 * @param array $file Uploaded file
	 */
	public function LogoUpdate( $file )
	{
		$fm = new Filemanager;
		$fm->MoveUpload($file['temp'], "uploads/custom/logo.jpg");
		$fm->Copy("uploads/custom/logo.jpg","admin/images/custom.jpg");
	}

	/**
	 * Execute a shell script after a PhPeace update
	 *
	 */
	public function PostInstall()
	{
		$va = new Varia();
		$conf = new Configuration();
		$script = $conf->Get("post_install_script");
		if($script!="")
		{
			$va->SetTimeLimit(900);
			$va->Exec($script);
			if($va->return_status!=0)
			{
				UserError("Post install script failed",array("script"=>$script,"return_code"=>$va->return_status),512);
			}
		}
	}
	
	/**
	 * Public paths
	 *
	 * @return array
	 */
	public function PublicPaths()
	{
		$pub_paths = array();
		$pub_paths['tools'] 	= "tools";
		$pub_paths['phpeace'] 	= "phpeace";
		$pub_paths['books'] 	= $this->ini->Get("books_path");
		$pub_paths['campaign'] 	= $this->ini->Get("campaign_path");
		$pub_paths['dodc'] 		= "dodc";
		$pub_paths['ecomm'] 	= "ecomm";
		$pub_paths['events'] 	= $this->ini->Get("events_path");
		$pub_paths['forum'] 	= $this->ini->Get("forum_path");
		$pub_paths['galleries']	= $this->ini->Get("gallery_path");
		$pub_paths['lists'] 	= $this->ini->Get("lists_path");
		$pub_paths['media'] 	= $this->ini->Get("media_path");
		$pub_paths['meet'] 		= "meet";
		$pub_paths['orgs'] 		= $this->ini->Get("org_path");
		$pub_paths['poll'] 		= $this->ini->Get("poll_path");
		$pub_paths['quotes'] 	= $this->ini->Get("quotes_path");
		$pub_paths['search'] 	= $this->ini->Get("search_path");
		$pub_paths['users'] 	= $this->ini->Get("users_path");
		$pub_paths['uss'] 		= "uss";
		$pub_paths['widgets'] 	= "widgets";
		return $pub_paths;
	}
	
	/**
	 * Module paths
	 * Subset of public paths which are part of a module installation
	 *
	 * @return array
	 */
	private function ModulePaths()
	{
		$paths = $this->PublicPaths();
		unset($paths['tools']);
		unset($paths['phpeace']);
		unset($paths['campaign']);
		unset($paths['events']);
		unset($paths['forum']);
		unset($paths['galleries']);
		unset($paths['poll']);
		unset($paths['search']);
		unset($paths['users']);
		return $paths;
	}
	
	/**
	 * Register a PhPeace client of this site
	 *
	 * @param string $install_key
	 * @param build $id_version
	 * @param name $name Installation name
	 * @param string $contact Name of mantainer
	 * @param string $email Email of mantainer
	 * @param string $admin_web URL of Admin interface
	 * @return integer ID of the new client
	 */
	public function Register($install_key,$id_version,$name,$contact,$email,$admin_web)
	{
		$id_client = 0;
		$client = $this->ClientCheck($install_key);
		if ( ! ($client['id_client'] > 0) )
		{
			$db =& Db::globaldb();
			$db->begin();
			$db->lock( "clients" );
			$id_client = $db->nextId( "clients", "id_client" );
			$sqlstr = "INSERT INTO clients (id_client,install_key,latest_version,last_contact,name,contact,email,approved,admin_web)
			 VALUES ($id_client,'$install_key',$id_version,'" . $db->GetTodayTime() . "','$name','$contact','$email',1,'$admin_web')";
			$res[] = $db->query( $sqlstr );
			Db::finish( $res, $db);
			$this->ClientModulesUpdate($id_client,array());
			$url = $this->ini->Get("admin_web") . "/phpeace/client.php?id=$id_client";
			$ah = new AdminHelper;
			$ah->WarnAdmin("New Client","New client registration: $name\nContact: $contact\nemail: $email\n$admin_web\nbuild: $id_version\n\nSee: $url\n\n");
		}
		return $id_client;
	}
	
	/**
	 * Return the registration link for this Phpeace instance
	 *
	 * @param integer $id_language
	 * @return string URL to go for registration
	 */
	public function RegisterLink($id_language)
	{
		return "{$this->phpeace_server}/phpeace/register.php?b=" . $this->build . "&k=" . $this->ini->Get("install_key") . "&admin=" . urlencode($this->ini->Get("admin_web")) . "&id_language=" . $id_language;
	}
	
	/**
	 * Inform Phpeace server about this Phpeace client configuration
	 * and retrieve any module update
	 *
	 */
	public function ServerUpdate()
	{
		if ($this->phpeace_server!="" && !$this->main)
		{
			$data = array();
			$data['from'] = "client_update";
			$data['install_key'] = $this->ini->Get("install_key");
			$data['admin_web'] = $this->ini->Get("admin_web");
			$data['php_version'] = phpversion();
			include_once(SERVER_ROOT."/../classes/modules.php");
			$modules = Modules::ModulesInfo();
			include_once(SERVER_ROOT."/../classes/varia.php");
			$v = new Varia();
			$data['modules'] = $v->Serialize($modules,false,false);
			$fm = new FileManager();
			$cmodules = $fm->PostData($this->phpeace_server,"/phpeace/actions.php",$data);
			$umodules = $v->Deserialize($cmodules,false);
			if(is_array($umodules))
			{
				foreach($umodules as $umod)
				{
					if($umod['internal']=="0")
					{
						foreach($modules as $mod)
						{
							if($mod['id_module']==$umod['id_module'] && $mod['active']!=$umod['active'])
							{
								Modules::Activate($umod['id_module'],$umod['active']);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * Build number of PhPeace server
	 *
	 * @return integer
	 */
	public function ServerBuildNumber()
	{
		$version_page = "$this->phpeace_server/phpeace/build.php";
		$fm = new FileManager;
		return $fm->Browse($version_page);
	}

	/**
	 * Verify wether a new update is available
	 *
	 * @return string Message
	 */
	public function VersionCheck()
	{
		include_once(SERVER_ROOT."/../classes/translator.php");
		$tr = new Translator(0,0);
		if ($this->phpeace_server!="")
		{
			$message = "";
			$res = $this->ServerBuildNumber();
			if (is_numeric($res))
			{
				if ($res < $this->build)
					$message = $tr->TranslateParams("phpeace_update_error_1",array($this->build,$res));
				if ($res == $this->build)
					$message = $tr->TranslateParams("phpeace_update_error_2",array($this->version,$this->build));
				if ($res > $this->build)
					$message = $this->VersionInstall($this->build + 1, true, true);
			}
			else
				$message = $tr->TranslateParams("phpeace_update_error_3",array($this->phpeace_server));
		}
		else
			$message = $tr->Translate("phpeace_update_error_4");
		return $message;
	}

	/**
	 * Install a new PhPeace update
	 *
	 * @param integer 	$build_new 		New build number
	 * @param boolean 	$download 		Wether to download the update package
	 * @param boolint 	$execute_update	Wether to execute the update script
786
	 * @param boolint 	$notify_server	Notify PhPeace server
787
	 * @param boolint 	$force_build	Force build number from DB instead of local constant
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
788 789
	 * @return string Message
	 */
790
	public function VersionInstall( $build_new, $download, $execute_update, $notify_server=true, $force_build=false )
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
	{
		include_once(SERVER_ROOT."/../classes/translator.php");
		include_once(SERVER_ROOT."/../classes/adminhelper.php");
		include_once(SERVER_ROOT."/../classes/log.php");
		include_once(SERVER_ROOT."/../classes/webservice.php");
		$log = new Log();
		$tr = new Translator(0,0);
		$fm = new FileManager;
		$ah = new AdminHelper;
		$ws = new WebService("phpeace");
		$update_filename = $this->FileNameUpdate($build_new) . ".tar.gz";
		$install_key = $this->ini->Get("install_key");
		if ($download)
		{
			$archive = "$this->phpeace_server/phpeace/download.php?id=$build_new&k=$install_key";
			$fm->DirAction($this->tpath,"check");
			$fm->DownLoad($archive, "$this->tpath/$update_filename",true);
			$log->Write("info","Downloading $update_filename");
			$server_hash = trim($fm->Browse($archive . "&hash=1"));

			$local_hash = $fm->Hash("$this->tpath/$update_filename");
			if($server_hash!=$local_hash)
			{
				UserError("PhPeace download failed",array('build'=>$build_new,'server_hash'=>$server_hash,'local_hash'=>$local_hash),256,true);
			}

			$ws_params = array();
			$ws_params['id_version'] = $build_new;
			$ws_params['key'] = $install_key;
			$server_hash2 = $ws->Call($this->phpeace_server,"HashUpdateFile",$ws_params);
			if($server_hash2=="" || $server_hash2!=$server_hash)
			{
				UserError("PhPeace server returned different hash for update file",array('build'=>$build_new,'server_hash'=>$server_hash,'server_hash_ws'=>$server_hash2),512);
			}
		}
		if ($fm->Size("$this->tpath/$update_filename",false) > MIN_PHPEACE_UPDATE_SIZE_KB)
		{
			include_once(SERVER_ROOT."/../classes/modules.php");
			include_once(SERVER_ROOT."/../classes/varia.php");
			$va = new Varia();
			$va->SetTimeLimit(600);
			$fm->DirDelete("pub/phpeace");
			$fm->DirDelete("pub/tools");
			$fm->TarExtract("$this->tpath/$update_filename","");
			$module_paths = $this->ModulePaths();
			foreach($this->PublicPaths() as $path=>$db_path)
			{
				if ($path!="phpeace" && $path!="tools")
				{
					$fm->DirDelete("pub/$db_path");
					if(in_array($path,$module_paths))
					{
						switch ($path)
						{
							case "ecomm":
								$module_path = "ecommerce";
							break;
							default:
								$module_path = $path;
							break;
						}
						if(Modules::IsActiveByPath($module_path))
							$fm->Rename("pub/_".$path,"pub/$db_path");
						else 
						{
							$fm->DirDelete("pub/_".$path);
							$fm->DirDelete("scripts/".$path);
						}
					}
					else 
					{
						$fm->Rename("pub/_".$path,"pub/$db_path");
					}
				}
			}
866 867 868 869 870 871 872 873 874
			$conf = new Configuration();
			$ui = $conf->Get("ui");
			if(!$ui) {
				include_once(SERVER_ROOT."/../classes/pagetypes.php");
				$pt = new PageTypes();
				include_once(SERVER_ROOT."/../classes/xsl.php");
				$xslm1 = new XslManager("global");
				$xsl1s = $xslm1->XslOutsourced();
				foreach($xsl1s as $xsl1)
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
875
				{
876 877 878 879 880 881 882 883 884
					$xslm1->id_pagetype = $xsl1['id_xsl'];
					$filename = "xsl0/" . $xslm1->XslFile($xsl1['id_xsl']);
					if($fm->Exists($filename))
					{
						$type = array_search($xslm1->id_pagetype,$pt->gtypes);
						$xsl = $fm->TextFileRead($filename);
						$xsl = $xslm1->OutputUpdate($xsl,$type);
						$xslm1->XslStoreWrite($xsl1['id_xsl'],0,"",$xsl);
					}
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
885
				}
886 887 888
				$xslm2 = new XslManager();
				$xsl2s = $xslm2->XslOutsourced();
				foreach($xsl2s as $xsl2)
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
889
				{
890 891 892 893 894 895 896 897 898
					$xslm2->id_pagetype = $xsl2['id_type'];
					$filename = "xsl0/" . $xslm2->XslFile($xsl2['id_xsl']);
					if($fm->Exists($filename))
					{
						$type = array_search($xslm2->id_pagetype,$pt->types);
						$xsl = $fm->TextFileRead($filename);
						$xsl = $xslm2->OutputUpdate($xsl,$type);
						$xslm2->XslStoreWrite($xsl2['id_xsl'],0,"",$xsl);
					}
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
899
				}
900 901 902
				$xslm3 = new XslManager("module");
				$xsl3s = $xslm3->XslOutsourced();
				foreach($xsl3s as $xsl3)
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
903
				{
904 905 906 907 908 909 910 911
					$xslm3->id_pagetype = $xsl3['id_module'];
					$filename = "xsl0/" . $xslm3->XslFile($xsl3['id_xsl']);
					if($fm->Exists($filename))
					{
						$xsl = $fm->TextFileRead($filename);
						$xsl = $xslm3->OutputUpdate($xsl,"");
						$xslm3->XslStoreWrite($xsl3['id_xsl'],0,"",$xsl);
					}
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
912 913 914 915
				}
			}
			if ($execute_update)
			{
916 917 918
				if($force_build) {
					$this->build = $this->ini->Get("script_version");
				}
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
				$log->Write("info","Executing update for version $build_new");
				include(SERVER_ROOT."/../classes/phpeace_updates.php");
				$pu = new PhPeaceUpdates($this->build);
				$pu->Update($build_new);
			}
			include_once(SERVER_ROOT."/../classes/sharedmem.php");
			$sm = new SharedMem(false);
			if($sm->IsAPC())
			{
				$sm->ResetAll();
			}
			$this->ini->ForceReload();
			$phpeace_new = new PhPeace();
			if ($phpeace_new->version != "")
			{
				$msg = $ah->MessageSet("phpeace_install_ok",array($build_new));
				if($ah->current_user_id>0)
					$ah->MessageSet("phpeace_install_warning",array($this->ini->Get("admin_web")));
				if ($this->main)
					$fm->HardCopy("$this->tpath/$update_filename","distrib/$update_filename");
939 940 941 942 943 944
				if($notify_server) {
					$wsparams = array();
					$wsparams['id_version'] = $build_new;
					$wsparams['key'] = $install_key;
					$ws->Call($this->phpeace_server,"UpdateClientVersion",$wsparams);
				}
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
945 946 947 948 949
			}
			else
			{
				$msg = $ah->MessageSet("phpeace_install_ko",array($build_new));
			}
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
950 951
			$fm->Delete("$this->tpath/$update_filename");
			$fm->DirRemove($this->tpath);
Francesco Iannuzzelli's avatar
Francesco Iannuzzelli committed
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
			if (!$this->main)
				$fm->DirRemove("xsl0");
			$fm->PostUpdate();
			$log->Write("info",$tr->Translate("phpeace_update") . " - $msg");
		}
		else 
		{
			$ah->MessageSet("phpeace_install_ko",array($build_new));
			UserError($tr->Translate("phpeace_update"),array("build"=>$build_new));
		}
		$tr->Reset(false);
		return $msg;
	}

	/**
	 * Search all XSL files for a pattern
	 *
	 * @param string 	$string 			What to search
	 * @param boolean 	$notify_support 	Whether to notify support
	 * @return array 	All matched files
	 */
	public function XslSearch($string,$notify_support=false)
	{
		$found = array();
		$fm = new FileManager();
		$command = "grep -li \"$string\" {$fm->path}/xsl/*/*.xsl";
		include_once(SERVER_ROOT."/../classes/varia.php");
		$v = new Varia();
		$matches = $v->Exec($command);
		if(count($matches)>0)
		{
			$admin_web = $this->ini->Get("admin_web");
			include_once(SERVER_ROOT."/../classes/pagetypes.php");
			$pt = new PageTypes();
			foreach($matches as $match)
			{
				$path_info = pathinfo($match);
				$type = $path_info['filename'];
				$id_style = substr($path_info['dirname'],strrpos($path_info['dirname'],"/")+1);
				if(array_key_exists($type,$pt->gtypes))
				{
					$url = "{$admin_web}/layout/xsl_global.php?id={$pt->gtypes[$type]}";
				}
				elseif(array_key_exists($type,$pt->types))
				{
					$url = "{$admin_web}/layout/xsl.php?id={$pt->types[$type]}&id_style=$id_style";
				}
				else 
				{
					include_once(SERVER_ROOT."/../classes/modules.php");
					$mod = Modules::ModuleGetId($type);
					$url = "{$admin_web}/layout/xsl_module.php?id={$mod['id_module']}&id_style=$id_style";
					
				}
				$xsl = array();
				$xsl['type'] = $type;
				$xsl['file'] = $match;
				$xsl['url'] = $url;
				$found[] = $xsl;		
			}
		}
		if(count($found)>0 && $notify_support)
		{
			include_once(SERVER_ROOT."/../classes/mail.php");
			$m = new Mail();
			$subject = "[INFO] XSL matches for \"$string\"";
			$message = "\"$string\" has been found in the following XSL stylesheets:\n";
			foreach($found as $line)
			{
				$message .= "Type: {$line['type']}\n{$line['url']}\n\n";
			}
			$m->SendMail("[email protected]","PhPeace Support",$subject,$message,array());
		}
		return $found;
	}
}

/**
 * Web services for PhPeace installations management
 *
 * @package PhPeace
 * @author Francesco Iannuzzelli <[email protected]>
 */
class PhPeaceWS
{
	/**
	 * Update Client installed version ID
	 *
	 * @param string $id_version	Client version ID (build number) 
	 * @param string $key 			Client installation key
	 * 
	 */
	public function UpdateClientVersion($id_version,$key)
	{
		$phpeace = new PhPeace();
		$client = $phpeace->ClientCheck($key);
		if ($client['approved'])
		{
			$phpeace->ClientUpdateLast($client['id_client'], $id_version);
		}
	}

	/**
	 * Get hash for specific version update file
	 *
	 * @param string $id_version	Version ID (build number) 
	 * @param string $key 			Client installation key
	 * @return string 				File hash
	 * 
	 */
	public function HashUpdateFile($id_version,$key)
	{
		$hash = "";
		$phpeace = new PhPeace();
		$client = $phpeace->ClientCheck($key);
		if ($client['approved'])
		{
			$fm = new FileManager;
			$filename = $phpeace->FileNameUpdate($id_version) . ".tar.gz";
			$hash = $fm->Hash("distrib/$filename");
		}
		return $hash;
	}
}
?>