PageRenderTime 200ms CodeModel.GetById 135ms app.highlight 59ms RepoModel.GetById 1ms app.codeStats 0ms

/protected/Common/PortalUtil.php

http://pradoportal.googlecode.com/
PHP | 898 lines | 767 code | 89 blank | 42 comment | 155 complexity | b6a30a4f4b603ea3ab172e7c9ecb7646 MD5 | raw file
  1<?php
  2/**
  3 * Prado Portal.
  4 *
  5 * @author Steen Rabol <steen.rabol@gmail.com>
  6 * @link http://www.pradoportal.dk/
  7 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
  8 * @license http://www.pradoportal.dk
  9 * @version $Id: PortalUtil.php 467 2011-01-25 17:24:30Z steen.rabol $
 10 * @package Pradoportal.Common
 11 *
 12 */
 13
 14/**
 15 *
 16 * @package Pradoportal.Common
 17 */
 18
 19Prado::using('System.Util.TVarDumper');
 20
 21class PortalUtil
 22{
 23	public static function fatalError($msg, $debug = false)
 24	{
 25		if($debug)
 26		{
 27			echo '<h1>Fatal Error</h1>';
 28			if(is_array($msg))
 29			{
 30				echo "<pre>";
 31				print_r($msg);
 32				echo "</pre>";
 33			}
 34			else
 35			{
 36				echo '<p>'.$msg.'</p>';
 37			}
 38
 39			if(!function_exists('debug_backtrace'))
 40			{
 41				return;
 42			}
 43			echo '<h2>Debug Backtrace</h2>';
 44			echo '<pre>';
 45			$index=-1;
 46			foreach(debug_backtrace() as $t)
 47			{
 48				$index++;
 49				if($index==0)  // hide the backtrace of this function
 50					continue;
 51				echo '#'.$index.' ';
 52				if(isset($t['file']))
 53					echo basename($t['file']) . ':' . $t['line'];
 54				else
 55					echo '<PHP inner-code>';
 56				echo ' -- ';
 57				if(isset($t['class']))
 58					echo $t['class'] . $t['type'];
 59				echo $t['function'] . '(';
 60				if(isset($t['args']) && sizeof($t['args']) > 0)
 61				{
 62					$count=0;
 63					foreach($t['args'] as $item)
 64					{
 65						if(is_string($item))
 66						{
 67							$str=htmlentities(str_replace("\r\n", "", $item), ENT_QUOTES);
 68							if (strlen($item) > 70)
 69								echo "'". substr($str, 0, 70) . "...'";
 70							else
 71								echo "'" . $str . "'";
 72						}
 73						else if (is_int($item) || is_float($item))
 74							echo $item;
 75						else if (is_object($item))
 76							echo get_class($item);
 77						else if (is_array($item))
 78							echo 'array(' . count($item) . ')';
 79						else if (is_bool($item))
 80							echo $item ? 'true' : 'false';
 81						else if ($item === null)
 82							echo 'NULL';
 83						else if (is_resource($item))
 84							echo get_resource_type($item);
 85						$count++;
 86						if (count($t['args']) > $count)
 87							echo ', ';
 88					}
 89				}
 90				echo ")\n";
 91			}
 92			echo '</pre>';
 93			exit(1);
 94		}
 95		else
 96		{
 97			echo '<h1>Fatal Error</h1>';
 98			if(is_array($msg))
 99			{
100				foreach($msg as $m)
101				{
102					echo '<p>'.$m.'</p>';
103				}
104			}
105			else if(is_object($msg))
106			{
107				var_dump($msg);
108			}
109			else
110			{
111				echo '<p>' . $msg . '<p>';
112			}
113		}
114
115		exit(0);
116	}
117	/**
118	 * @parm $portletname is the name to check if is installed
119	 */
120	public static function IsPortletInstalled($portletname)
121	{
122		$application	= Prado::getApplication();
123		$db				= $application->DataAccess;
124		$portletid		= $db->createCommand("select id from tblportlets where name='$portletname'")->queryScalar();
125		return TPropertyValue::ensureBoolean($portletid);
126	}
127
128	public static function getAvailablePortalLayouts()
129	{
130		$application	= Prado::getApplication();
131		$basePath		= $application->PortalBasePath . "/protected/Layouts/Portal/" . $application->Parameters['ThemeName'];
132		$layouts		= array();
133
134		if(!is_dir($basePath))
135		{
136			$this->reportError(1,"Could not find layout directory $basePath");
137		}
138
139		$folder = @opendir($basePath);
140		while($file = @readdir($folder))
141		{
142			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($basePath.'/'.$file))
143			{
144				$path_parts = pathinfo($file);
145				if($path_parts['extension'] == "php")
146				{
147
148					$clsName = basename($path_parts['basename'],".php");
149
150					if(!class_exists($clsName,false))
151					{
152						$clsPath = 'Application.Layouts.Portal.' . $application->Parameters['ThemeName'] . '.' . $clsName;
153						Prado::using($clsPath);
154					}
155					$obj = new $clsName();
156					if($obj->Type == 1)
157					{
158						$layouts[] = array("id" => $clsName,"name" =>$obj->Name);
159					}
160				}
161			}
162		}
163		closedir($folder);
164		return $layouts;
165	}
166
167	public static function getAvailableAdminThemes()
168	{
169		$application	= Prado::getApplication();
170		$basePath		= $application->PortalBasePath . "/themes/Admin/";
171		$themes			= array();
172
173		if(!is_dir($basePath))
174		{
175			$this->reportError(1,"Could not find theme directory $basePath");
176		}
177
178		$folder = @opendir($basePath);
179		while($dir = @readdir($folder))
180		{
181			if($dir !== '.' && $dir !== '..' && $dir !== '.svn' && is_dir($basePath.'/'.$dir))
182			{
183				$themes[] = $dir;
184			}
185		}
186
187		closedir($folder);
188		return $themes;
189	}
190
191	public static function getAvailablePortalThemes()
192	{
193		$application	= Prado::getApplication();
194		$basePath		= $application->PortalBasePath . "/themes/Portal/";
195		$themes			= array();
196
197		if(!is_dir($basePath))
198		{
199			$this->reportError(1,"Could not find theme directory $basePath");
200		}
201
202		$folder = @opendir($basePath);
203		while($dir = @readdir($folder))
204		{
205			if($dir !== '.' && $dir !== '..' && $dir !== '.svn' && is_dir($basePath.'/'.$dir))
206			{
207				$themes[] = $dir;
208			}
209		}
210		closedir($folder);
211		return $themes;
212	}
213
214	public static function return_bytes($val)
215	{
216		$val = trim($val);
217		$last = strtolower($val{strlen($val)-1});
218		switch($last)
219		{
220			// The 'G' modifier is available since PHP 5.1.0
221			case 'g':
222				$val *= 1024;
223			case 'm':
224				$val *= 1024;
225			case 'k':
226				$val *= 1024;
227		}
228
229		return $val;
230	}
231
232	public static function return_letter_size($fsize)
233	{
234		$retval = "";
235		// Format size:
236		if ($fsize > ((1024 * 1024) * 1024))
237		{
238			$retval = number_format(((($fsize / 1024) / 1024) / 1024), 2) . ' GB';
239		}
240		elseif($fsize > (1024 * 1024))
241		{
242			$retval = number_format((($fsize / 1024) / 1024), 2) . ' MB';
243		}
244		elseif ($fsize > 1000)
245		{
246			$retval = number_format(($fsize/1024), 2) . ' KB';
247		}
248		else
249		{
250			$retval = $fsize . ' Bytes';
251		}
252
253		return $retval;
254	}
255
256	public static function isUTF8($str)
257	{
258		if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32"))
259		{
260			return true;
261		}
262		else
263		{
264			return false;
265		}
266	}
267
268	public static function getCookie($cookiename, $default_value = null)
269	{
270		$ret_val = $default_value;
271		$application	= Prado::getApplication();
272
273		foreach($application->Request->Cookies as $cookie)
274		{
275			if($cookie->Name == $cookiename)
276			{
277				return $cookie;
278			}
279		}
280
281		return $ret_val;
282	}
283
284	public static function getCookieValue($cookiename, $default_value = null)
285	{
286		$ret_val		= $default_value;
287		$application	= Prado::getApplication();
288
289		foreach($application->Request->Cookies as $cookie)
290		{
291			if($cookie->Name == $cookiename)
292			{
293				return $cookie->Value;
294			}
295		}
296
297		return $ret_val;
298	}
299
300	public static function Log($msg)
301	{
302		PortalUtil::LogAlert($msg);
303	}
304
305	public static function LogAlert($msg,$level = TLogger::ALERT)
306	{
307		Prado::log(TVarDumper::dump($msg),$level);
308	}
309
310	public static function Info($msg)
311	{
312		Prado::trace(TVarDumper::dump($msg));
313	}
314
315	public static function Debug($msg)
316	{
317		Prado::using('Application.Common.3rdParty.dBug');
318		new dBug($msg);
319	}
320
321	/**
322	 * @return Return a array with all system pages
323	 */
324	public static function getAvailableSystemPages()
325	{
326		$application	= Prado::getApplication();
327		$basePath		= $application->BasePath . "/Pages/System";
328		$layouts 		= array();
329
330		if(!is_dir($basePath))
331			$this->reportError(1,"Could not find layout directory $basePath");
332
333		$folder = @opendir($basePath);
334		while($file = @readdir($folder))
335		{
336			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($basePath.'/'.$file))
337			{
338				$path_parts = pathinfo($file);
339				if($path_parts['extension'] == "php")
340				{
341
342					$layouts[] = array("name" => "System." . basename($path_parts['basename'],".php"));
343				}
344			}
345		}
346		closedir($folder);
347		return $layouts;
348	}
349
350	public static function getAvailableAdminPages()
351	{
352		$application	= Prado::getApplication();
353		$basePath		= $application->BasePath . "/Pages/Admin";
354		$layouts 		= array();
355
356		if(!is_dir($basePath))
357			$this->reportError(1,"Could not find layout directory $basePath");
358
359		$folder = @opendir($basePath);
360		while($file = @readdir($folder))
361		{
362			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($basePath.'/'.$file))
363			{
364				$path_parts = pathinfo($file);
365				if($path_parts['extension'] == "php")
366				{
367					$layouts[] = array("name" => "Admin." . basename($path_parts['basename'],".php"));
368				}
369			}
370		}
371		closedir($folder);
372		return $layouts;
373	}
374
375	public static function AvailablePagesInPath($path)
376	{
377		$application	= Prado::getApplication();
378		$basePath		= $application->BasePath . "/Pages/$path";
379		$layouts 		= array();
380
381		if(!is_dir($basePath))
382		{
383			return $layouts;
384		}
385		$folder = @opendir($basePath);
386		while($file = @readdir($folder))
387		{
388			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($basePath.'/'.$file))
389			{
390				$path_parts = pathinfo($file);
391				if($path_parts['extension'] == "php")
392				{
393					$layouts[] = array("name" => "$path." . basename($path_parts['basename'],".php"));
394				}
395			}
396		}
397		closedir($folder);
398		return $layouts;
399	}
400
401	public static function getFilesInPath($path, $arrayprefix = null)
402	{
403		$application	= Prado::getApplication();
404		$files	 		= array();
405
406		if(!is_dir($path))
407		{
408			return false;
409		}
410
411		$folder = @opendir($path);
412		while($file = @readdir($folder))
413		{
414			if($file!=='.' && $file!=='..' && $file!=='.svn' && !is_dir($path.'/'.$file))
415			{
416				if($arrayprefix === null)
417				{
418					$files[] = $file;
419				}
420				else
421				{
422					$files[] = array($arrayprefix => $file);
423				}
424			}
425		}
426		closedir($folder);
427		return $files;
428	}
429
430	public static function GetCssClassesInPortlet($p_portlet)
431	{
432		$pCss			= null;
433		$application	= Prado::getApplication();
434		$p_file			= $application->BasePath . "/Portlets/" . $p_portlet . "/Common/" . $p_portlet ."Common.php";
435		$p_class		= $p_portlet . 'Common';
436		if(!class_exists($p_portlet.'Common',false))
437		{
438			Prado::using('Application.Portlets.' . $p_portlet . '.Common.' . $p_portlet . 'Common');
439		}
440
441		return call_user_func($p_class . '::GetCssClasses');
442
443	}
444
445	public static function GetCssClassesInAllPortlets()
446	{
447		$application	= Prado::getApplication();
448		$db				= $application->DataAccess;
449		$pDr			= $db->createCommand("select name from tblportlets")->query();
450		$pCss			= array();
451
452		if($pDr)
453		{
454			foreach($pDr as $p)
455			{
456				$p_portlet	= $p['name'];
457				$pres	= PortalUtil::GetCssClassesInPortlet($p_portlet);
458				if($pres !== null)
459				{
460					$pCss = array_merge($pCss,$pres);
461				}
462			}
463		}
464
465		return $pCss;
466	}
467
468	public static function CreateDirStructure($p_path)
469	{
470		if(is_dir($p_path) || $p_path == '' )
471		{
472			return;
473		}
474
475		try
476		{
477			return mkdir($p_path,0777,true);
478		}
479		catch (Exception $e)
480		{
481			throw new PortalException(1,sprintf("code %d msg: %s dir: %s",$e->getErrorCode(),$e->getErrorMessage(),$p_path));
482		}
483	}
484
485	public static function xCreateDirStructure($p_path)
486	{
487	    if (!file_exists($p_path))
488		{
489	        $_open_basedir_ini = ini_get('open_basedir');
490
491	        if (DIRECTORY_SEPARATOR=='/')
492			{
493	            /* unix-style paths */
494	            $_dir = $p_path;
495	            $_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY);
496	            $_new_dir = ($_dir{0}=='/') ? '/' : getcwd().'/';
497
498	            if($_use_open_basedir = !empty($_open_basedir_ini))
499				{
500	                $_open_basedirs = explode(':', $_open_basedir_ini);
501	            }
502	        }
503			else
504			{
505	            /* other-style paths */
506	            $_dir = str_replace('\\','/', $p_path);
507	            $_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY);
508	            if (preg_match('!^((//)|([a-zA-Z]:/))!', $_dir, $_root_dir))
509				{
510	                /* leading "//" for network volume, or "[letter]:/" for full path */
511	                $_new_dir = $_root_dir[1];
512	                /* remove drive-letter from _dir_parts */
513	                if (isset($_root_dir[3])) array_shift($_dir_parts);
514	            }
515				else
516				{
517	                $_new_dir = str_replace('\\', '/', getcwd()).'/';
518	            }
519
520	            if($_use_open_basedir = !empty($_open_basedir_ini))
521				{
522	                $_open_basedirs = explode(';', str_replace('\\', '/', $_open_basedir_ini));
523	            }
524	        }
525
526	        /* all paths use "/" only from here */
527	        foreach ($_dir_parts as $_dir_part)
528			{
529	            $_new_dir .= $_dir_part;
530
531	            if ($_use_open_basedir)
532				{
533	                // do not attempt to test or make directories outside of open_basedir
534	                $_make_new_dir = false;
535	                foreach ($_open_basedirs as $_open_basedir)
536					{
537	                    if (substr($_new_dir, 0, strlen($_open_basedir)) == $_open_basedir)
538						{
539	                        $_make_new_dir = true;
540	                        break;
541	                    }
542	                }
543	            }
544				else
545				{
546	                $_make_new_dir = true;
547	            }
548
549	            if ($_make_new_dir && !file_exists($_new_dir) && !@mkdir($_new_dir) && !is_dir($_new_dir))
550				{
551	               trigger_error("problem creating directory '" . $_new_dir . "'");
552	                return false;
553	            }
554	            $_new_dir .= '/';
555	        }
556	    }
557	}
558
559	public static function LicensInformation()
560	{
561		$licinfo = array();
562		$licinfo['PRODUCT']				= 'Prado Portal';
563		$licinfo['LICTYPE']				= 'Open Source';
564		$licinfo['CUSTNAME']			= 'Get Your own Open Source licens';
565		$licinfo['CUSTCONTACTNAME']		= 'Open source is free, but donations are welcome.';
566		$licinfo['CUSTCONTACTEMAIL']	= 'licens[at]pradoportal.dk';
567
568		$licfile = Prado::getPathOfNamespace('Application.Data') . '/' . 'licens.dat';
569
570		if(file_exists($licfile))
571		{
572			try
573			{
574				Prado::using('Application.Common.PortalLicens');
575				$pl 	= new PortalLicens();
576				$vinfo 	= $pl->validate(file_get_contents($licfile));
577
578				if($vinfo['RESULT'] == 'OK')
579				{
580					if($vinfo['DATA']['PRODUCT'] === 'pradoportal' && $vinfo['DATA']['LICTYPE'] === 'opensource' && $vinfo['DATA']['CUSTCONTACTEMAIL'] === 'info@pradoportal.dk')
581					{
582						$licinfo['PRODUCT']				= 'Prado Portal';
583						$licinfo['LICTYPE']				= 'Open Source';
584						$licinfo['CUSTNAME']			= 'Get Your own Open Source licens';
585						$licinfo['CUSTCONTACTNAME']		= 'Open source is free, but donations are welcome.';
586						$licinfo['CUSTCONTACTEMAIL']	= 'licens[at]pradoportal.dk';
587					}
588					else
589					{
590						$licinfo = $vinfo['DATA'];
591						$licinfo['PRODUCT']	= ($vinfo['DATA']['PRODUCT'] === 'pradoportal' ? 'Prado Portal': $vinfo['DATA']['PRODUCT']);
592						$licinfo['LICTYPE'] = ($vinfo['DATA']['LICTYPE'] === 'opensource' ? 'Open Source' : $vinfo['DATA']['LICTYPE']);
593					}
594				}
595			}
596			catch(Exception $e)
597			{
598				$licinfo['PRODUCT']				= 'Prado Portal';
599				$licinfo['LICTYPE']				= 'Open Source';
600				$licinfo['CUSTNAME']			= 'Get Your own Open Source licens';
601				$licinfo['CUSTCONTACTNAME']		= 'Open source is free, but donations are welcome.';
602				$licinfo['CUSTCONTACTEMAIL']	= 'licens[at]pradoportal.dk';
603			}
604		}
605
606		return $licinfo;
607	}
608
609	public static function LicenseType()
610	{
611		$licinfo = self::LicensInformation();
612		return $licinfo['LICTYPE'];
613	}
614
615	public static function DeleteDirStructure($dir,$p_deldir = false)
616	{
617		$current_dir = @opendir($dir);
618		while($entryname = readdir($current_dir))
619		{
620			if(is_dir("$dir/$entryname") and ($entryname != "." and $entryname!=".."))
621			{
622				PortalUtil::DeleteDirStructure("${dir}/${entryname}",true);
623			}
624			elseif($entryname != "." and $entryname!="..")
625			{
626				@unlink("${dir}/${entryname}");
627			}
628		}
629
630		@closedir($current_dir);
631
632		if($p_deldir)
633		{
634			@rmdir($dir);
635		}
636	}
637
638	public static function MakePassword()
639	{
640		$makepass	= "";
641		$salt		= "abchefghjkmnpqrstuvwxyz0123456789";
642		srand((double)microtime()*1000000);
643		$i = 0;
644		while ($i <= 7)
645		{
646			$num = rand() % 33;
647			$tmp = substr($salt, $num, 1);
648			$makepass = $makepass . $tmp;
649			$i++;
650		}
651		return ($makepass);
652	}
653
654	public static function getIP()
655	{
656		// Find the user's IP address. (but don't let it give you 'unknown'!)
657		if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_CLIENT_IP']) && (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['HTTP_CLIENT_IP']) == 0 || preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) != 0))
658		{
659			// We have both forwarded for AND client IP... check the first forwarded for as the block - only switch if it's better that way.
660			if (strtok($_SERVER['HTTP_X_FORWARDED_FOR'], '.') != strtok($_SERVER['HTTP_CLIENT_IP'], '.') && '.' . strtok($_SERVER['HTTP_X_FORWARDED_FOR'], '.') == strrchr($_SERVER['HTTP_CLIENT_IP'], '.') && (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['HTTP_X_FORWARDED_FOR']) == 0 || preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) != 0))
661				$_SERVER['REMOTE_ADDR'] = implode('.', array_reverse(explode('.', $_SERVER['HTTP_CLIENT_IP'])));
662			else
663				$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CLIENT_IP'];
664		}
665		if (!empty($_SERVER['HTTP_CLIENT_IP']) && (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['HTTP_CLIENT_IP']) == 0 || preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) != 0))
666		{
667			// Since they are in different blocks, it's probably reversed.
668			if (strtok($_SERVER['REMOTE_ADDR'], '.') != strtok($_SERVER['HTTP_CLIENT_IP'], '.'))
669				$_SERVER['REMOTE_ADDR'] = implode('.', array_reverse(explode('.', $_SERVER['HTTP_CLIENT_IP'])));
670			else
671				$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CLIENT_IP'];
672		}
673		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
674		{
675			// If there are commas, get the last one.. probably.
676			if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false)
677			{
678				$ips = array_reverse(explode(', ', $_SERVER['HTTP_X_FORWARDED_FOR']));
679
680				// Go through each IP...
681				foreach ($ips as $i => $ip)
682				{
683					// Make sure it's in a valid range...
684					if (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $ip) != 0 && preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) == 0)
685						continue;
686
687					// Otherwise, we've got an IP!
688					$_SERVER['REMOTE_ADDR'] = trim($ip);
689					break;
690				}
691			}
692			// Otherwise just use the only one.
693			elseif (preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['HTTP_X_FORWARDED_FOR']) == 0 || preg_match('~^((0|10|172\.16|192\.168|255|127\.0)\.|unknown)~', $_SERVER['REMOTE_ADDR']) != 0)
694				$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
695		}
696		elseif (!isset($_SERVER['REMOTE_ADDR']))
697			$_SERVER['REMOTE_ADDR'] = '';
698	}
699
700	public static function getGUID()
701	{
702		// The field names refer to RFC 4122 section 4.1.2
703		return sprintf(/*'%04x%04x-%04x-%03x4-%04x-%04x%04x%04x'*/ '%04x%04x-%04x-4%03x-%04x-%04x%04x%04x',
704				        mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
705				        mt_rand(0, 65535), // 16 bits for "time_mid"
706				        mt_rand(0, 4095),  // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
707				        bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
708	            		// 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
709    	        		// (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
710        	    		// 8 bits for "clk_seq_low"
711	    			    mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
712    				);
713	}
714
715	public static function getPagesAsUrl()
716	{
717		$app		= Prado::getApplication();
718		$db			= $app->DataAccess;
719		$service	= $app->Service;
720		$p_name	= array();
721		$p_url	= array();
722
723		$pages	= $db->createCommand("select fullpath from tblpages")->query()->readAll();
724		if($pages && is_array($pages) && count($pages) > 0)
725		{
726			foreach($pages as $page)
727			{
728				$p_name[]	= "{" . $page['fullpath'] . "}";
729				$p_url[]	= $service->constructUrl($page['fullpath']);
730			}
731		}
732		return array($p_name,$p_url);
733	}
734
735	public static function getMemoryUsage($real = true)
736	{
737		return (memory_get_peak_usage($real) / 1024) . " kb";
738	}
739
740	public static function GenId($seqname='ppseq', $startID=1)
741	{
742		$db	= Prado::getApplication()->DbConnection;
743		if($db)
744		{
745			try
746			{
747				$getnext	= sprintf("update %s set id=id+1;", $seqname);
748				$result		= $db->createCommand($getnext)->execute();
749				return $db->createCommand("select id from $seqname")->queryScalar();
750			}
751			catch(Exception $e)
752			{
753				$db->createCommand(sprintf("drop table if exists %s",$seqname))->execute();
754				$db->createCommand(sprintf("create table %s (id int not null)",$seqname))->execute();
755				$db->createCommand(sprintf("insert into %s values (%d)",$seqname, $startID-1))->execute();
756				return PortalUtil::GenID($seqname,$startID);
757			}
758		}
759		else
760		{
761			PortalUtil::fatalError("Faild to connect to the database");
762		}
763	}
764
765	public static function CreateSequence($seqname='adodbseq',$startID=1)
766	{
767		$db	= Prado::getApplication()->DbConnection;
768		if($db)
769		{
770			try
771			{
772				$db->createCommand(sprintf("create table %s (id int not null)",$seqname))->execute();
773			}
774			catch(Exception $e)
775			{
776				PortalUtil::fatalError("Db error: " . $e->getMessage());
777			}
778		}
779		else
780		{
781			PortalUtil::fatalError("Faild to connect to the database");
782		}
783	}
784
785	public static function DropSequence($seqname='adodbseq')
786	{
787		$db	= Prado::getApplication()->DbConnection;
788		if($db)
789		{
790			try
791			{
792				$db->createCommand(sprintf("drop table if exists %s",$seqname))->execute();
793			}
794			catch(Exception $e)
795			{
796				PortalUtil::fatalError("Db error: " . $e->getMessage());
797			}
798		}
799		else
800		{
801			PortalUtil::fatalError("Faild to connect to the database");
802		}
803	}
804
805	public static function PathName($p_path, $p_createdir = false)
806	{
807		$retval = "";
808		$retval = str_replace('\\','/',$p_path);
809		if(substr($retval,-1) != '/')
810		{
811			$retval .= '/';
812		}
813		// Remove double //
814		$retval = str_replace('//','/',$retval);
815
816		if($p_createdir)
817		{
818			@mkdir($p_path,0777,true);
819		}
820		return $retval;
821	}
822
823	public static function DbTableExists($tblname)
824	{
825		$db			= Prado::getApplication()->DbConnection;
826		$sql		= "show tables like '$tblname'";
827		$dbresult	= $db->createCommand($sql)->query();
828
829		if($dbresult === null)
830		{
831			$retval = false;
832		}
833		else
834		{
835			$retval = true;
836		}
837
838		return $retval;
839	}
840
841	public static function CreateLangString($string, $key = 'APPLICATION')
842	{
843		if($string === "" || empty($string))
844		{
845			return;
846		}
847		
848		Prado::using('Application.Common.Data.PortalLanguageRecord');
849		Prado::using('Application.Common.Data.PortalLanguageStringRecord');
850
851		// Get Active languages
852		$actLang	= PortalLanguageRecord::finder()->findAll("active =?",1);
853
854		if($actLang !== 0 && is_array($actLang) && count($actLang) > 0)
855		{
856			foreach($actLang as $aLang)
857			{
858				$lsRec = PortalLanguageStringRecord::finder()->findByculture_AND_fromvalue($aLang->culture,$string);
859				if($lsRec === null)
860				{
861					$lsRec				= new PortalLanguageStringRecord();
862					$lsRec->culture		= $aLang->culture;
863					$lsRec->lkey		= 'APPLICATION';
864					$lsRec->fromvalue	= $string;
865					$lsRec->tovalue		= $string;
866					$lsRec->save();	
867				}
868			}
869		}
870	}
871
872	public static function request_uri()
873	{
874		$uri	= "";
875		if (isset($_SERVER['REQUEST_URI']))
876		{
877			$uri = $_SERVER['REQUEST_URI'];
878		}
879		else
880		{
881			if (isset($_SERVER['argv']))
882			{
883				$uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['argv'][0];
884			}
885			elseif (isset($_SERVER['QUERY_STRING']))
886			{
887				$uri = $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
888			}
889			else
890			{
891				$uri = $_SERVER['SCRIPT_NAME'];
892			}
893		}
894
895		return $uri;
896	}
897}
898?>