diff --git a/framework/src/Maveriks/Http/Response.php b/framework/src/Maveriks/Http/Response.php new file mode 100644 index 000000000..ae851417d --- /dev/null +++ b/framework/src/Maveriks/Http/Response.php @@ -0,0 +1,338 @@ + + */ +class Response +{ + /** + * @var string content stream + */ + + protected $content = ""; + protected $sourceName = ""; + protected $headers = array(); + protected $charset; + protected $statusCode; + protected $extension; + protected $filename; + protected $version; + protected $statusText; + + protected static $mimeType = array( + 'ai' => 'application/postscript', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/octet-stream', + 'ccad' => 'application/clariscad', 'cdf' => 'application/x-netcdf', 'class' => 'application/octet-stream', + 'cpio' => 'application/x-cpio', 'cpt' => 'application/mac-compactpro', 'csh' => 'application/x-csh', + 'csv' => 'application/csv', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', + 'dms' => 'application/octet-stream', 'doc' => 'application/msword', 'drw' => 'application/drafting', + 'dvi' => 'application/x-dvi', 'dwg' => 'application/acad', 'dxf' => 'application/dxf', + 'dxr' => 'application/x-director', 'eot' => 'application/vnd.ms-fontobject', 'eps' => 'application/postscript', + 'exe' => 'application/octet-stream', 'ez' => 'application/andrew-inset', + 'flv' => 'video/x-flv', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', + 'bz2' => 'application/x-bzip', '7z' => 'application/x-7z-compressed', 'hdf' => 'application/x-hdf', + 'hqx' => 'application/mac-binhex40', 'ico' => 'image/vnd.microsoft.icon', 'ips' => 'application/x-ipscript', + 'ipx' => 'application/x-ipix', 'js' => 'application/x-javascript', 'latex' => 'application/x-latex', + 'lha' => 'application/octet-stream', 'lsp' => 'application/x-lisp', 'lzh' => 'application/octet-stream', + 'man' => 'application/x-troff-man', 'me' => 'application/x-troff-me', 'mif' => 'application/vnd.mif', + 'ms' => 'application/x-troff-ms', 'nc' => 'application/x-netcdf', 'oda' => 'application/oda', + 'otf' => 'font/otf', 'pdf' => 'application/pdf', + 'pgn' => 'application/x-chess-pgn', 'pot' => 'application/mspowerpoint', 'pps' => 'application/mspowerpoint', + 'ppt' => 'application/mspowerpoint', 'ppz' => 'application/mspowerpoint', 'pre' => 'application/x-freelance', + 'prt' => 'application/pro_eng', 'ps' => 'application/postscript', 'roff' => 'application/x-troff', + 'scm' => 'application/x-lotusscreencam', 'set' => 'application/set', 'sh' => 'application/x-sh', + 'shar' => 'application/x-shar', 'sit' => 'application/x-stuffit', 'skd' => 'application/x-koan', + 'skm' => 'application/x-koan', 'skp' => 'application/x-koan', 'skt' => 'application/x-koan', + 'smi' => 'application/smil', 'smil' => 'application/smil', 'sol' => 'application/solids', + 'spl' => 'application/x-futuresplash', 'src' => 'application/x-wais-source', 'step' => 'application/STEP', + 'stl' => 'application/SLA', 'stp' => 'application/STEP', 'sv4cpio' => 'application/x-sv4cpio', + 'sv4crc' => 'application/x-sv4crc', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', + 'swf' => 'application/x-shockwave-flash', 't' => 'application/x-troff', + 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', + 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'tr' => 'application/x-troff', + 'tsp' => 'application/dsptype', 'ttf' => 'font/ttf', + 'unv' => 'application/i-deas', 'ustar' => 'application/x-ustar', + 'vcd' => 'application/x-cdlink', 'vda' => 'application/vda', 'xlc' => 'application/vnd.ms-excel', + 'xll' => 'application/vnd.ms-excel', 'xlm' => 'application/vnd.ms-excel', 'xls' => 'application/vnd.ms-excel', + 'xlw' => 'application/vnd.ms-excel', 'zip' => 'application/zip', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', + 'aiff' => 'audio/x-aiff', 'au' => 'audio/basic', 'kar' => 'audio/midi', 'mid' => 'audio/midi', + 'midi' => 'audio/midi', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpga' => 'audio/mpeg', + 'ra' => 'audio/x-realaudio', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', + 'rpm' => 'audio/x-pn-realaudio-plugin', 'snd' => 'audio/basic', 'tsi' => 'audio/TSP-audio', 'wav' => 'audio/x-wav', + 'asc' => 'text/plain', 'c' => 'text/plain', 'cc' => 'text/plain', 'css' => 'text/css', 'etx' => 'text/x-setext', + 'f' => 'text/plain', 'f90' => 'text/plain', 'h' => 'text/plain', 'hh' => 'text/plain', 'htm' => 'text/html', + 'html' => 'text/html', 'm' => 'text/plain', 'rtf' => 'text/rtf', 'rtx' => 'text/richtext', 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', 'tsv' => 'text/tab-separated-values', 'tpl' => 'text/template', 'txt' => 'text/plain', + 'xml' => 'text/xml', 'avi' => 'video/x-msvideo', 'fli' => 'video/x-fli', 'mov' => 'video/quicktime', + 'movie' => 'video/x-sgi-movie', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', + 'qt' => 'video/quicktime', 'viv' => 'video/vnd.vivo', 'vivo' => 'video/vnd.vivo', 'gif' => 'image/gif', + 'ief' => 'image/ief', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', + 'pbm' => 'image/x-portable-bitmap', 'pgm' => 'image/x-portable-graymap', 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', 'ppm' => 'image/x-portable-pixmap', 'ras' => 'image/cmu-raster', + 'rgb' => 'image/x-rgb', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'xbm' => 'image/x-xbitmap', + 'xpm' => 'image/x-xpixmap', 'xwd' => 'image/x-xwindowdump', 'ice' => 'x-conference/x-cooltalk', + 'iges' => 'model/iges', 'igs' => 'model/iges', 'mesh' => 'model/mesh', 'msh' => 'model/mesh', + 'silo' => 'model/mesh', 'vrml' => 'model/vrml', 'wrl' => 'model/vrml', + 'mime' => 'www/mime', 'pdb' => 'chemical/x-pdb', 'xyz' => 'chemical/x-pdb' + ); + protected static $statusTexts = array( + 100 => 'Continue', + 101 => 'Switching Protocols', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 307 => 'Temporary Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Requested Range Not Satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + ); + + public function __construct($content = "", $status = 200, $headers = array()) + { + if (! empty($content)) { + $this->setContent($content); + } + + if (! empty($headers)) { + $this->headers = $headers; + + if (! isset($this->headers['Date'])) { + $this->setDate(new \DateTime(null, new \DateTimeZone('UTC'))); + } + } + + $this->setStatusCode($status); + $this->setProtocolVersion("1.0"); + } + + /** + * @param string $content content string to stream + */ + public function setContent($content) + { + $this->content = $content; + + // a string was set as content, now define as text/html + $this->setHeader("Content-Type", "text/html"); + } + + /** + * @param string $filename file to stream + * @throws \Exception + */ + public function loadFromFile($filename) + { + if (! file_exists($filename)) { + throw new \Exception("Unable to find file: $filename"); + } + + $this->filename = $filename; + $this->content = file_get_contents($this->filename); + $fileInfo = pathinfo($filename, PATHINFO_EXTENSION); + $this->setExtension($fileInfo); + $this->setSourceName(basename($filename)); + } + + public function setExtension($extension) + { + $this->extension = $extension; + } + + /** + * Returns the extension of the file. + * \SplFileInfo::getExtension() is not available before PHP 5.3.6 + * + * @return string The extension + */ + public function getExtension() + { + return $this->extension; + } + + /** + * Returns the mime type of the file. (improved by erik) + * + * The mime type is guessed using the functions finfo(), mime_content_type() + * and the system binary "file" (in this order), depending on which of those + * is available on the current operating system. + * + * @author Erik Amaru Ortiz + * @return string|null The guessed mime type (i.e. "application/pdf") + */ + public function getMimeType() + { + if (array_key_exists($this->getExtension(), self::$mimeType)) { + return self::$mimeType[$this->getExtension()]; + } + + if (! empty($this->filename)) { + if (class_exists('finfo')) { + $finfo = new \finfo; + $mimeType = $finfo->file($this->filename, FILEINFO_MIME); + + if (preg_match('/([\w\-]+\/[\w\-]+); charset=(\w+)/', $mimeType, $match)) { + return $match[1]; + } + } + + if (function_exists('mime_content_type')) { + return mime_content_type($this->filename); + } + } + + return 'application/octet-stream'; + } + + public function setSourceName($sourceName) + { + $this->sourceName = $sourceName; + } + + public function setProtocolVersion($version) + { + $this->version = $version; + } + + public function setHeader($header, $value) + { + $this->headers[$header] = $value; + } + + public function setDate(\DateTime $date) + { + $date->setTimezone(new \DateTimeZone('UTC')); + $this->headers['Date'] = $date->format('D, d M Y H:i:s') . ' GMT'; + } + + /** + * Retrieves the response charset. + * + * @return string Character set + */ + public function getCharset() + { + return $this->charset; + } + + /** + * Sets the response charset. + * + * @param string $charset + * @return string Character set + */ + public function setCharset($charset) + { + $this->charset = $charset; + } + + public function setStatusCode($code, $text = null) + { + $this->statusCode = (int) $code; + $this->statusText = false === $text ? '' : (null === $text ? self::$statusTexts[$this->statusCode] : $text); + } + + public function prepare() + { + if (! empty($this->sourceName)) { + //TODO define a setter for this + //$this->setHeader('Content-Disposition', 'attachment; filename="'. $this->sourceName . '"' ); + } + + // Fix Content-Type + $charset = $this->charset ?: 'UTF-8'; + + if (! isset($this->headers['Content-Type'])) { + $this->headers['Content-Type'] = $this->getMimeType(); + } + + if ( + 0 === strpos($this->headers['Content-Type'], 'text/') && + false === strpos($this->headers['Content-Type'], 'charset') + ) { + // add the charset + $this->headers['Content-Type'] = $this->headers['Content-Type'].'; charset='.$charset; + } + + // Fix Content-Length + if (isset($this->headers['Transfer-Encoding'])) { + unset($this->headers['Content-Length']); + } + + + } + + public function sendHeaders() + { + // headers have already been sent by the developer + if (headers_sent()) { + return; + } + + $this->prepare(); + + // status + header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)); + + // headers + foreach ($this->headers as $name => $value) { + if (is_array($value)) { + foreach ($value as $v) { + header($name.': '.$v, false); + } + } else { + header($name.': '.$value, false); + } + } + } + + public function sendContent() + { + echo $this->content; + } + + public function send() + { + $this->sendHeaders(); + $this->sendContent(); + + if (function_exists('fastcgi_finish_request')) { + fastcgi_finish_request(); + } + } +} \ No newline at end of file diff --git a/framework/src/Maveriks/Pattern/Mvc/PhtmlView.php b/framework/src/Maveriks/Pattern/Mvc/PhtmlView.php new file mode 100644 index 000000000..da35dbd7d --- /dev/null +++ b/framework/src/Maveriks/Pattern/Mvc/PhtmlView.php @@ -0,0 +1,82 @@ +getTpl(); + + if (empty($tplFile)) { + throw new \Exception('ERROR: template file was not set!'); + } + + foreach ($this->getTemplateDir() as $dir) { + if (file_exists($dir . DIRECTORY_SEPARATOR . $tplFile)) { + $tplFile = $dir . DIRECTORY_SEPARATOR . $tplFile; + break; + } + } + + if (! file_exists($tplFile)) { + throw new \Exception('ERROR: template file '.$tplFile.' does not exist!'); + } + + extract($this->data); + + include $tplFile; + + if (! empty(self::$extend)) { + $tplFile = ''; //$this->getTemplateDir() . DIRECTORY_SEPARATOR . self::$extend . '.phtml'; + + foreach ($this->getTemplateDir() as $dir) { + if (file_exists($dir . DIRECTORY_SEPARATOR . self::$extend . '.phtml')) { + $tplFile = $dir . DIRECTORY_SEPARATOR . self::$extend . '.phtml'; + break; + } + } + + if (! file_exists($tplFile)) { + throw new \Exception('ERROR: Layout template file '.$tplFile.' does not exist!'); + } + + extract($this->data); + + include $tplFile; + } + } + + static public function extend($name) + { + self::$extend = $name; + } + + static public function block($name, $default = '') + { + if (is_string($default)) { + if (array_key_exists($name, self::$blocks)) { + $callback = self::$blocks[$name]; + $callback(); + } else { + return $default; + } + + return; + } elseif ($default instanceof \Closure) { + self::$blocks[$name] = $default; + } + } +} diff --git a/framework/src/Maveriks/Pattern/Mvc/View.php b/framework/src/Maveriks/Pattern/Mvc/View.php new file mode 100644 index 000000000..77babf783 --- /dev/null +++ b/framework/src/Maveriks/Pattern/Mvc/View.php @@ -0,0 +1,299 @@ + + * @link https://github.com/phpalchemy/phpalchemy + * @copyright Copyright 2012 Erik Amaru Ortiz + * @license http://www.opensource.org/licenses/mit-license.php MIT License + * @package Maveriks\Pattern\Mvc + */ +abstract class View +{ + /** + * Contains all variables that are available on template file + * + * @var array + */ + protected $data = array(); + + /** + * Contains the absolute paths where templates are stored + * + * @var array + */ + protected $templateDir = array(); + + /** + * Contains the absolute path where the engine store the cache files + * + * @var string + */ + protected $cacheDir = ''; + + /** + * String to store the output string that is sent by http response + * + * @var string + */ + protected $content = ''; + + /** + * Relative path of template file + * + * @var string + */ + protected $tpl = ''; + + /** + * Cache flag to specify if templating cache is enabled or not + * + * @var string + */ + protected $cache = false; + + /** + * Charset Encodig + * + * @var string + */ + protected $charset = 'UTF-8'; + + /** + * Debug flag to indicate to template engine is a debug environment + * Defaults false + * + * @var bool + */ + public $debug = false; + + /** + * @param string $tpl template file + */ + public function __construct($tpl = '') + { + $this->tpl = $tpl; + } + + /** + * Sets template file path (absolute or partial path) + * + * @param string $tpl contains the path of template file + */ + public function setTpl($tpl) + { + $this->tpl = $tpl; + } + + /** + * Gets template file + */ + public function getTpl() + { + return $this->tpl; + } + + /** + * Sets the base path where the engine can be find all templates + * + * @param string $path contains the absolute path where templates are stored + */ + public function setTemplateDir($path) + { + $this->templateDir[] = $path; + } + + /** + * Gets the templates files base path + * + * @return array returns the templates base path + */ + public function getTemplateDir() + { + return $this->templateDir; + } + + /** + * Sets cache directory path + * + * @param string $path cache directory path + */ + public function setCacheDir($dir) + { + $this->cacheDir = $dir; + + if (! is_dir($this->cacheDir)) { + $this->createDir($this->cacheDir); + } + } + + /** + * Gets cache directory path + * + * @return string contains cache directory path + */ + public function getCacheDir() + { + return $this->cacheDir; + } + + /** + * Enable/Disable templating cache + * + * @param bool $value boolean value to enable or not cache + */ + public function enableCache($value) + { + $this->cache = $value ? true: false; + } + + /** + * Enable/Disable debug mode of template engine + * + * @param bool $value boolean value to enable or not debug mode + */ + public function enableDebug($value) + { + $this->debug = $value ? true: false; + } + + + /** + * Sets charset encoding for template engine + * @param string $charset conatins a valid charset like UTF-8, ISO-8859-1 (latin), etc. + */ + public function setCharset($charset) + { + $this->charset = $charset; + } + + /** + * Gets charset encoding + * + * @return string charset encoding + */ + public function getCharset() + { + return $this->charset; + } + + /** + * Alias of method assign() + * + * @param string $name name or key to store teh value passed + * @param string $value variable value + */ + public function set($name, $value = null) + { + $this->assign($name, $value); + } + + /** + * Assings a variable to the template file + * + * @param string $name name or key to store teh value passed + * @param string $value variable value + */ + public function assign($name, $value = null) + { + if (is_string($name)) { + return $this->data[$name] = $value; + } + + if (is_array($name)) { + $this->assignFromArray($name); + return null; + } + + throw new \InvalidArgumentException("Invalid data type for key, '" .gettype($name) . "' given."); + } + + /** + * Gets a variable that was previously assigned + * + * @param string $name name or key to store teh value passed + * @param string $value variable value + */ + public function get($name) + { + if (!isset($this->data[$name])) { + throw new \InvalidArgumentException("Variable '$name' doesn't exist."); + } + + return $this->data[$name]; + } + + public function exists($name) + { + return array_key_exists($name, $this->data); + } + + /** + * Gets final template parsed output string + * + * @return string parsed output + */ + public function getOutput() + { + $output = ''; + \ob_start(); + $this->render(); + $output = \ob_get_contents(); + \ob_end_clean(); + + return $output; + } + + /** + * Render the output string (To override by child class) + */ + abstract public function render(); + + /** + * Multiple variable assignment + * + * @param array $data associative array conatining variables, the keys are used as variables names + */ + protected function assignFromArray($data) + { + if (! is_array($data)) { + throw new \InvalidArgumentException( + "Invalid data type: argument should be array, '" .gettype($data) . "' given." + ); + } + + foreach ($data as $key => $value) { + $this->assign($key, $value); + } + } + + protected function createDir($strPath, $rights = 0777) + { + $folderPath = array($strPath); + $oldumask = umask(0); + + while (!@is_dir(dirname(end($folderPath))) + && dirname(end($folderPath)) != '/' + && dirname(end($folderPath)) != '.' + && dirname(end($folderPath)) != '' + ) { + array_push($folderPath, dirname(end($folderPath))); + } + + while ($parentFolderPath = array_pop($folderPath)) { + if (! @is_dir($parentFolderPath)) { + if (! @mkdir($parentFolderPath, $rights)) { + throw new \Exception("Templating Engine Error: Can't create folder '$parentFolderPath'"); + } + } + } + + umask($oldumask); + } +} diff --git a/framework/src/Maveriks/Util/ClassLoader.php b/framework/src/Maveriks/Util/ClassLoader.php new file mode 100644 index 000000000..a09a890ae --- /dev/null +++ b/framework/src/Maveriks/Util/ClassLoader.php @@ -0,0 +1,117 @@ +SplClassLoader that loads classes of the + * specified namespace. + * + * @param string $ns The namespace to use. + */ + public function __construct() + { + defined("DS") || define("DS", DIRECTORY_SEPARATOR); + defined("NS") || define("NS", "\\"); + + spl_autoload_register(array($this, 'loadClass')); + } + + /** + * @return \Maveriks\Util\ClassLoader + */ + public static function getInstance() + { + if (is_null(self::$instance)) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * Gets the base include path for all class files in the namespace of this class loader. + * + * @return string $includePath + */ + public function getIncludePaths() + { + return self::$includePath; + } + + /** + * Uninstalls this class loader from the SPL autoloader stack. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + public function add($sourceDir, $namespace = "") + { + if (empty($namespace)) { + self::$includePath[] = $sourceDir . (substr($sourceDir, -1) == DS ? "" : DS); + } else { + self::$includePathNs[$namespace] = $sourceDir . (substr($sourceDir, -1) == DS ? "" : DS); + } + } + + function loadClass($className) + { + $classPath = str_replace(NS, DS, $className); + + if (false !== strpos($className, NS)) {// has namespace? + $lastPos = strpos($className, NS); + $mainNs = substr($className, 0, $lastPos); + + if (isset(self::$includePathNs[$mainNs])) { + if (file_exists(self::$includePathNs[$mainNs] . $classPath . ".php")) { + require self::$includePathNs[$mainNs] . $classPath . ".php"; + return true; + } else { + return false; + } + } + } + + foreach (self::$includePath as $path) { + $filename = $path . $classPath . ".php"; + //var_dump($filename); + + if (file_exists($filename)) { + require $filename; + return true; + } + } + + return false; + } + + /** + * Loads the given class or interface. + * + * @param string $className The name of the class to load. + * @return void + */ + public function loadClass2($className) + { + if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) { + $fileName = ''; + $namespace = ''; + + if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) { + $namespace = substr($className, 0, $lastNsPos); + $className = substr($className, $lastNsPos + 1); + $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; + } + + $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; + + require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; + } + } +} \ No newline at end of file diff --git a/framework/src/Maveriks/Util/Common.php b/framework/src/Maveriks/Util/Common.php new file mode 100644 index 000000000..9f927707a --- /dev/null +++ b/framework/src/Maveriks/Util/Common.php @@ -0,0 +1,128 @@ + + * @param string $pattern pattern for native glob function + * @param int|string $flags any valid flag for glob function + * @param bool $onlyFiles to filter return array with only matched files, or all matched results + * @return array array containing the recursive glob results + * + * Example: + * + * Common::rglob("/example/path/*"); + * + * it will returns: + * + * Array + * ( + * [0] => /example/path/README.txt + * [1] => /example/path/composer.json + * [4] => /example/path/one/one_text.txt + * [6] => /example/path/two/two_text.txt + * [7] => /example/path/two/two_one/two_one_text.txt + * [8] => /example/path/two/two_one/build.json + * ) + * + * Example 2: + * + * Common::rglob("/example/path/*.json"); + * + * It will returns: + * + * Array + * ( + * [0] => /example/path/composer.json + * [1] => /example/path/two/two_one/build.json + * ) + */ + public static function rglob($pattern, $flags = 0, $onlyFiles = false) + { + $singlePattern = basename($pattern); + + if (strpos($singlePattern, "*") !== false) { + $path = rtrim(str_replace($singlePattern, "", $pattern), DIRECTORY_SEPARATOR); + } else { + $singlePattern = ""; + $path = $pattern; + } + + $files = glob("$path/$singlePattern", $flags); + $dirs = glob("$path/*", GLOB_MARK|GLOB_ONLYDIR|GLOB_NOSORT); + + foreach ($dirs as $dir) { + $files = array_merge($files, self::rglob("$dir/$singlePattern", $flags)); + } + + if ($onlyFiles) { + $files = array_filter($files, function($v) { return is_dir($v) ? false : true;}); + } + + return $files; + } + + /** + * Returns the last version given a pattern of file name + * + * @param string $pattern a valid pattern for glob(...) native function + * @param int $flag php flags for glob(...) native function + * @return int|string + * + * Example: + * - Given the following files inside a directory: + * /example/path/myApplication-v1.tar + * /example/path/myApplication-v2.tar + * /example/path/myApplication-v3.tar + * /example/path/myApplication-v5.tar + * /example/path/myApplication-v7.tar + * + * $lastVer = ProcessMaker\Util\Common::getLastVersion("/example/path/myApplication-*.tar"); + * + * It will returns: 7 + */ + public static function getLastVersion($pattern, $flag = 0) + { + $files = glob($pattern, $flag); + $maxVersion = 0; + + $pattern = str_replace("*", '([0-9\.]+)', basename($pattern)); + + foreach ($files as $file) { + $filename = basename($file); + + if (preg_match('/'.$pattern.'/', $filename, $match)) { + + if ($maxVersion < $match[1]) { + $maxVersion = $match[1]; + } + } + } + + return $maxVersion; + } + + public static function parseIniFile($filename) + { + $data = @parse_ini_file($filename, true); + $result = array(); + + if ($data === false) { + throw new \Exception("Error parsing ini file: $filename"); + } + + foreach ($data as $key => $value) { + if (strpos($key, ':') !== false) { + list($key, $subSection) = explode(':', $key); + $result[trim($key)][trim($subSection)] = $value; + } else { + $result[$key] = $value; + } + } + + return $result; + } +} \ No newline at end of file diff --git a/framework/src/Maveriks/Util/Logger.php b/framework/src/Maveriks/Util/Logger.php new file mode 100644 index 000000000..26235bc39 --- /dev/null +++ b/framework/src/Maveriks/Util/Logger.php @@ -0,0 +1,73 @@ + + */ +class Logger +{ + private static $instance; + private $logFile; + private $fp; + + protected function __construct() + { + $this->logFile = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'processmaker.log'; + if (! file_exists($this->logFile)) { + if (! touch($this->logFile)) { + error_log("ProcessMaker Log file can't be created!"); + } + chmod($this->logFile, 0777); + } + + $this->fp = fopen($this->logFile, "a+"); + } + + public static function getInstance() + { + if (is_null(self::$instance)) { + self::$instance = new Logger(); + } + + return self::$instance; + } + + public function setLogLine() + { + $args = func_get_args(); + + $this->setLog(date('Y-m-d H:i:s') . " "); + + foreach ($args as $str) { + $this->setLog((is_string($str) ? $str : var_export($str, true)) . PHP_EOL); + } + } + + public function setLogInline() + { + $args = func_get_args(); + $this->setLog(date('Y-m-d H:i:s') . " "); + + foreach ($args as $str) { + $this->setLog((is_string($str) ? $str : var_export($str, true)) . " "); + } + } + + public function setLog($str) + { + fwrite($this->fp, $str); + } + + public static function log() + { + $me = Logger::getInstance(); + $args = func_get_args(); + + call_user_func_array(array($me, 'setLogLine'), $args); + } +} + diff --git a/framework/src/Maveriks/WebApplication.php b/framework/src/Maveriks/WebApplication.php new file mode 100644 index 000000000..d9cf56ae7 --- /dev/null +++ b/framework/src/Maveriks/WebApplication.php @@ -0,0 +1,359 @@ +rootDir = $rootDir; + $this->workflowDir = $rootDir . DS . "workflow" . DS; + } + + /** + * @return string + */ + public function getRootDir() + { + return $this->rootDir; + } + + /** + * @param string $requestUri + */ + public function setRequestUri($requestUri) + { + $this->requestUri = $requestUri; + } + + /** + * @return string + */ + public function getRequestUri() + { + return $this->requestUri; + } + + public function route() + { + if (substr($this->requestUri, 1, 3) == "api") { + return self::RUNNING_API; + } else { + return self::RUNNING_WORKFLOW; + } + } + + public function run($type = "") + { + switch ($type) { + case self::SERVICE_API: + $request = $this->parseApiRequestUri(); + $this->loadEnvironment($request["workspace"]); + + Util\Logger::log("API::Dispatching ".$_SERVER["REQUEST_METHOD"]." ".$request["uri"]); + $this->dispatchApiRequest($request["uri"], $request["version"]); + Util\Logger::log("API::End Dispatching ".$_SERVER["REQUEST_METHOD"]." ".$request["uri"]); + break; + } + } + + /** + * This method dispatch rest/api service + * + * @author Erik Amaru Ortiz + */ + public function dispatchApiRequest($uri, $version = "1.0") + { + // to handle a request with "OPTIONS" method + if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { + header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEADERS'); + header('Access-Control-Allow-Headers: authorization, content-type'); + header("Access-Control-Allow-Credentials", "false"); + header('Access-Control-Max-Age: 60'); + die(); + } + + /* + * Enable this header to allow "Cross Domain AJAX" requests; + * This works because processmaker is handling correctly requests with method 'OPTIONS' + * that automatically is sent by a client using XmlHttpRequest or similar. + */ + header('Access-Control-Allow-Origin: *'); + + // $servicesDir contains directory where Services Classes are allocated + $servicesDir = $this->workflowDir . 'engine' . DS . 'src' . DS . 'Services' . DS; + // $apiDir - contains directory to scan classes and add them to Restler + $apiDir = $servicesDir . 'Api' . DS; + // $apiIniFile - contains file name of api ini configuration + $apiIniFile = $servicesDir . DS . 'api.ini'; + // $authenticationClass - contains the class name that validate the authentication for Restler + $authenticationClass = 'Services\\Api\\OAuth2\\Server'; + // $pmOauthClientId - contains PM Local OAuth Id (Web Designer) + $pmOauthClientId = 'x-pm-local-client'; + + /* + * Load Api ini file for Rest Service + */ + $apiIniConf = array(); + if (file_exists($apiIniFile)) { + $apiIniConf = Util\Common::parseIniFile($apiIniFile); + } + + // Setting current workspace to Api class + \ProcessMaker\Services\Api::setWorkspace(SYS_SYS); + // TODO remove this setting on the future, it is not needed, but if it is not present is throwing a warning + //\Luracast\Restler\Format\HtmlFormat::$viewPath = $servicesDir . 'oauth2/views'; + + // create a new Restler instance + $rest = new \Luracast\Restler\Restler(); + // setting api version to Restler + $rest->setAPIVersion($version); + // adding $authenticationClass to Restler + $rest->addAuthenticationClass($authenticationClass, ''); + + // Setting database connection source + list($host, $port) = strpos(DB_HOST, ':') !== false ? explode(':', DB_HOST) : array(DB_HOST, ''); + $port = empty($port) ? '' : ";port=$port"; + \Services\Api\OAuth2\Server::setDatabaseSource(DB_USER, DB_PASS, DB_ADAPTER.":host=$host;dbname=".DB_NAME.$port); + + // Setting default OAuth Client id, for local PM Web Designer + \Services\Api\OAuth2\Server::setPmClientId($pmOauthClientId); + + require_once $this->workflowDir . "engine/src/Extension/Restler/UploadFormat.php"; + //require_once PATH_CORE + + //$rest->setSupportedFormats('JsonFormat', 'XmlFormat', 'UploadFormat'); + //$rest->setOverridingFormats('UploadFormat', 'JsonFormat', 'XmlFormat', 'HtmlFormat'); + $rest->setOverridingFormats('JsonFormat', 'UploadFormat'); + + // Override $_SERVER['REQUEST_URI'] to Restler handles the current url correctly + + $isPluginRequest = strpos($uri, '/plugin-') !== false ? true : false; + + if ($isPluginRequest) { + $tmp = explode('/', $uri); + array_shift($tmp); + $tmp = array_shift($tmp); + $tmp = explode('-', $tmp); + $pluginName = $tmp[1]; + $uri = str_replace('/plugin-'.$pluginName, '', $uri); + } + + $_SERVER['REQUEST_URI'] = $uri; + + if (! $isPluginRequest) { // if it is not a request for a plugin endpoint + // scan all api directory to find api classes + $classesList = Util\Common::rglob($apiDir . "/*"); + + foreach ($classesList as $classFile) { + if (pathinfo($classFile, PATHINFO_EXTENSION) === 'php') { + $namespace = '\\Services\\' . str_replace( + DIRECTORY_SEPARATOR, + '\\', + str_replace('.php', '', str_replace($servicesDir, '', $classFile)) + ); + //var_dump($namespace); + $rest->addAPIClass($namespace); + } + } + + // adding aliases for Restler + if (array_key_exists('alias', $apiIniConf)) { + foreach ($apiIniConf['alias'] as $alias => $aliasData) { + if (is_array($aliasData)) { + foreach ($aliasData as $label => $namespace) { + $namespace = '\\' . ltrim($namespace, '\\'); + $rest->addAPIClass($namespace, $alias); + } + } + } + } + } else { + // hook to get rest api classes from plugins +// if (class_exists('PMPluginRegistry')) { +// $pluginRegistry = & PMPluginRegistry::getSingleton(); +// $plugins = $pluginRegistry->getRegisteredRestServices(); +// +// if (is_array($plugins) && array_key_exists($pluginName, $plugins)) { +// foreach ($plugins[$pluginName] as $class) { +// $rest->addAPIClass($class['namespace']); +// } +// } +// } + } + + $rest->handle(); + } + + public function parseApiRequestUri() + { + $url = explode("/", $this->requestUri); + array_shift($url); + array_shift($url); + $version = array_shift($url); + $workspace = array_shift($url); + $restUri = ""; + + foreach ($url as $urlPart) { + $restUri .= "/" . $urlPart; + } + + return array( + "uri" => $restUri, + "version" => $version, + "workspace" => $workspace + ); + } + + public function loadEnvironment($workspace) + { + $lang = "en"; + + define('SYS_LANG', $lang); + define('PATH_SEP', DIRECTORY_SEPARATOR); + + define('PATH_TRUNK', $this->rootDir . PATH_SEP); + define('PATH_OUTTRUNK', realpath($this->rootDir . '/../') . PATH_SEP); + define('PATH_HOME', $this->rootDir . PATH_SEP . 'workflow' . PATH_SEP); + + define('PATH_HTML', PATH_HOME . 'public_html' . PATH_SEP); + define('PATH_RBAC_HOME', PATH_TRUNK . 'rbac' . PATH_SEP); + define('PATH_GULLIVER_HOME', PATH_TRUNK . 'gulliver' . PATH_SEP); + define('PATH_GULLIVER', PATH_GULLIVER_HOME . 'system' . PATH_SEP); //gulliver system classes + define('PATH_GULLIVER_BIN', PATH_GULLIVER_HOME . 'bin' . PATH_SEP); //gulliver bin classes + define('PATH_TEMPLATE', PATH_GULLIVER_HOME . 'templates' . PATH_SEP); + define('PATH_THIRDPARTY', PATH_GULLIVER_HOME . 'thirdparty' . PATH_SEP); + define('PATH_RBAC', PATH_RBAC_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP); //to enable rbac version 2 + define('PATH_RBAC_CORE', PATH_RBAC_HOME . 'engine' . PATH_SEP); + define('PATH_CORE', PATH_HOME . 'engine' . PATH_SEP); + define('PATH_SKINS', PATH_CORE . 'skins' . PATH_SEP); + define('PATH_SKIN_ENGINE', PATH_CORE . 'skinEngine' . PATH_SEP); + define('PATH_METHODS', PATH_CORE . 'methods' . PATH_SEP); + define('PATH_XMLFORM', PATH_CORE . 'xmlform' . PATH_SEP); + define('PATH_CONFIG', PATH_CORE . 'config' . PATH_SEP); + define('PATH_PLUGINS', PATH_CORE . 'plugins' . PATH_SEP); + define('PATH_HTMLMAIL', PATH_CORE . 'html_templates' . PATH_SEP); + define('PATH_TPL', PATH_CORE . 'templates' . PATH_SEP); + define('PATH_TEST', PATH_CORE . 'test' . PATH_SEP); + define('PATH_FIXTURES', PATH_TEST . 'fixtures' . PATH_SEP); + define('PATH_RTFDOCS', PATH_CORE . 'rtf_templates' . PATH_SEP); + define('PATH_DYNACONT', PATH_CORE . 'content' . PATH_SEP . 'dynaform' . PATH_SEP); + define('SYS_UPLOAD_PATH', PATH_HOME . "public_html/files/" ); + define('PATH_UPLOAD', PATH_HTML . 'files' . PATH_SEP); + define('PATH_WORKFLOW_MYSQL_DATA', PATH_CORE . 'data' . PATH_SEP . 'mysql' . PATH_SEP); + define('PATH_RBAC_MYSQL_DATA', PATH_RBAC_CORE . 'data' . PATH_SEP . 'mysql' . PATH_SEP); + define('FILE_PATHS_INSTALLED', PATH_CORE . 'config' . PATH_SEP . 'paths_installed.php' ); + define('PATH_WORKFLOW_MSSQL_DATA', PATH_CORE . 'data' . PATH_SEP . 'mssql' . PATH_SEP); + define('PATH_RBAC_MSSQL_DATA', PATH_RBAC_CORE . 'data' . PATH_SEP . 'mssql' . PATH_SEP); + define('PATH_CONTROLLERS', PATH_CORE . 'controllers' . PATH_SEP); + define('PATH_SERVICES_REST', PATH_CORE . 'services' . PATH_SEP . 'rest' . PATH_SEP); + + require_once PATH_GULLIVER . PATH_SEP . 'class.bootstrap.php'; + + spl_autoload_register(array("Bootstrap", "autoloadClass")); + + \Bootstrap::registerClass("G", PATH_GULLIVER . "class.g.php"); + \Bootstrap::registerClass("System", PATH_HOME . "engine/classes/class.system.php"); + + // define autoloading for others + \Bootstrap::registerClass("wsBase", PATH_HOME . "engine/classes/class.wsBase.php"); + \Bootstrap::registerClass('Xml_Node', PATH_GULLIVER . "class.xmlDocument.php"); + \Bootstrap::registerClass('XmlForm_Field_TextPM', PATH_HOME . "engine/classes/class.XmlForm_Field_TextPM.php"); + \Bootstrap::registerClass('XmlForm_Field_SimpleText', PATH_GULLIVER . "class.xmlformExtension.php"); + \Bootstrap::registerClass('XmlForm_Field', PATH_GULLIVER . "class.xmlform.php"); + + //\Bootstrap::registerDir('model', PATH_CORE . 'classes' . PATH_SEP . 'model'); + //\Bootstrap::registerDir('rbac/model', PATH_RBAC_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'model'); + + //\Bootstrap::LoadThirdParty("smarty/libs", "Smarty.class"); + + \Bootstrap::registerSystemClasses(); + + + $config = \System::getSystemConfiguration(); + + define('DEBUG_SQL_LOG', $config['debug_sql']); + define('DEBUG_TIME_LOG', $config['debug_time']); + define('DEBUG_CALENDAR_LOG', $config['debug_calendar']); + define('MEMCACHED_ENABLED', $config['memcached']); + define('MEMCACHED_SERVER', $config['memcached_server']); + define('TIME_ZONE', $config['time_zone']); + + + // set include path + set_include_path( + PATH_CORE . PATH_SEPARATOR . + PATH_THIRDPARTY . PATH_SEPARATOR . + PATH_THIRDPARTY . 'pear' . PATH_SEPARATOR . + PATH_RBAC_CORE . PATH_SEPARATOR . + get_include_path() + ); + + + /* + * Setting Up Workspace + */ + + // include the server installed configuration + require_once FILE_PATHS_INSTALLED; + + define('SYS_SYS', $workspace); + + // defining system constant when a valid server environment exists + define( 'PATH_LANGUAGECONT', PATH_DATA . "META-INF" . PATH_SEP ); + define( 'PATH_CUSTOM_SKINS', PATH_DATA . 'skins' . PATH_SEP ); + define( 'PATH_TEMPORAL', PATH_C . 'dynEditor/' ); + define( 'PATH_DB', PATH_DATA . 'sites' . PATH_SEP ); + + $workspaceDir = PATH_DB . $workspace; + + // smarty constants + define( 'PATH_SMARTY_C', PATH_C . 'smarty' . PATH_SEP . 'c' ); + define( 'PATH_SMARTY_CACHE', PATH_C . 'smarty' . PATH_SEP . 'cache' ); + + + //***************** PM Paths DATA ************************** + define('PATH_DATA_SITE', PATH_DATA . 'sites/' . SYS_SYS . '/'); + define('PATH_DOCUMENT', PATH_DATA_SITE . 'files/'); + define('PATH_DATA_MAILTEMPLATES', PATH_DATA_SITE . 'mailTemplates/'); + define('PATH_DATA_PUBLIC', PATH_DATA_SITE . 'public/'); + define('PATH_DATA_REPORTS', PATH_DATA_SITE . 'reports/'); + define('PATH_DYNAFORM', PATH_DATA_SITE . 'xmlForms/'); + define('PATH_IMAGES_ENVIRONMENT_FILES', PATH_DATA_SITE . 'usersFiles' . PATH_SEP); + define('PATH_IMAGES_ENVIRONMENT_USERS', PATH_DATA_SITE . 'usersPhotographies' . PATH_SEP); + + if (is_file(PATH_DATA_SITE.PATH_SEP . '.server_info')) { + $SERVER_INFO = file_get_contents(PATH_DATA_SITE.PATH_SEP.'.server_info'); + $SERVER_INFO = unserialize($SERVER_INFO); + + define('SERVER_NAME', $SERVER_INFO ['SERVER_NAME']); + define('SERVER_PORT', $SERVER_INFO ['SERVER_PORT']); + } else { + echo "WARNING! No server info found!"; + } + + // create memcached singleton + \Bootstrap::LoadClass('memcached'); + //$memcache = PMmemcached::getSingleton( SYS_SYS ); + + \Propel::init(PATH_CONFIG . "databases.php"); + } +} \ No newline at end of file diff --git a/framework/src/templates/Exception.phtml b/framework/src/templates/Exception.phtml new file mode 100644 index 000000000..873864706 --- /dev/null +++ b/framework/src/templates/Exception.phtml @@ -0,0 +1,88 @@ + + + + + + Runtime Exception. + + + +
+

System Exception.

+
+

+ RuntimeException: + +

+
+
+ +
    + getTrace() as $line ) { + if (isset($line['class'])) { + echo '
  1. At ' . $line['class'].$line['type'].$line['function'] + . '()
    in '.$line['file'].' line '.$line['line'].'
  2. '; + } else{ + echo '
  3. At ' . $line['function'] . '() in '.$line['file'].' line '.$line['line'].'
  4. '; + } + } ?> +
+
+
+ + \ No newline at end of file diff --git a/src/ProcessMaker/Core/SplClassLoader.php b/src/ProcessMaker/Core/SplClassLoader.php deleted file mode 100644 index eb018702b..000000000 --- a/src/ProcessMaker/Core/SplClassLoader.php +++ /dev/null @@ -1,157 +0,0 @@ -. - */ - -/** - * SplClassLoader implementation that implements the technical interoperability - * standards for PHP 5.3 namespaces and class names. - * - * http://groups.google.com/group/php-standards/web/psr-0-final-proposal?pli=1 - * - * // Example which loads classes for the Doctrine Common package in the - * // Doctrine\Common namespace. - * $classLoader = new SplClassLoader('Doctrine\Common', '/path/to/doctrine'); - * $classLoader->register(); - * - * @license http://www.opensource.org/licenses/mit-license.html MIT License - * @author Jonathan H. Wage - * @author Roman S. Borschel - * @author Matthew Weier O'Phinney - * @author Kris Wallsmith - * @author Fabien Potencier - */ -class SplClassLoader -{ - private $_fileExtension = '.php'; - private $_namespace; - private $_includePath; - private $_namespaceSeparator = '\\'; - - /** - * Creates a new SplClassLoader that loads classes of the - * specified namespace. - * - * @param string $ns The namespace to use. - */ - public function __construct($ns = null, $includePath = null) - { - $this->_namespace = $ns; - $this->_includePath = $includePath; - } - - /** - * Sets the namespace separator used by classes in the namespace of this class loader. - * - * @param string $sep The separator to use. - */ - public function setNamespaceSeparator($sep) - { - $this->_namespaceSeparator = $sep; - } - - /** - * Gets the namespace seperator used by classes in the namespace of this class loader. - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->_namespaceSeparator; - } - - /** - * Sets the base include path for all class files in the namespace of this class loader. - * - * @param string $includePath - */ - public function setIncludePath($includePath) - { - $this->_includePath = $includePath; - } - - /** - * Gets the base include path for all class files in the namespace of this class loader. - * - * @return string $includePath - */ - public function getIncludePath() - { - return $this->_includePath; - } - - /** - * Sets the file extension of class files in the namespace of this class loader. - * - * @param string $fileExtension - */ - public function setFileExtension($fileExtension) - { - $this->_fileExtension = $fileExtension; - } - - /** - * Gets the file extension of class files in the namespace of this class loader. - * - * @return string $fileExtension - */ - public function getFileExtension() - { - return $this->_fileExtension; - } - - /** - * Installs this class loader on the SPL autoload stack. - */ - public function register() - { - spl_autoload_register(array($this, 'loadClass')); - } - - /** - * Uninstalls this class loader from the SPL autoloader stack. - */ - public function unregister() - { - spl_autoload_unregister(array($this, 'loadClass')); - } - - /** - * Loads the given class or interface. - * - * @param string $className The name of the class to load. - * @return void - */ - public function loadClass($className) - { - if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) { - $fileName = ''; - $namespace = ''; - - if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) { - $namespace = substr($className, 0, $lastNsPos); - $className = substr($className, $lastNsPos + 1); - $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; - } - - $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; - - require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; - } - } -} \ No newline at end of file diff --git a/src/framework/Maveriks/Util/ClassLoader.php b/src/framework/Maveriks/Util/ClassLoader.php new file mode 100644 index 000000000..bda55000d --- /dev/null +++ b/src/framework/Maveriks/Util/ClassLoader.php @@ -0,0 +1,111 @@ +SplClassLoader that loads classes of the + * specified namespace. + * + * @param string $ns The namespace to use. + */ + public function __construct() + { + defined("DS") || define("DS", DIRECTORY_SEPARATOR); + defined("NS") || define("NS", "\\"); + + spl_autoload_register(array($this, 'loadClass')); + } + + /** + * @return \ProcessMaker\Core\ClassLoader + */ + public static function getInstance() + { + if (is_null(self::$instance)) { + self::$instance = new self(); + } + + return self::$instance; + } + + /** + * Gets the base include path for all class files in the namespace of this class loader. + * + * @return string $includePath + */ + public function getIncludePaths() + { + return self::$includePath; + } + + /** + * Uninstalls this class loader from the SPL autoloader stack. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + public function add($namespace, $sourceDir) + { + if (empty($namespace)) { + self::$includePath[] = $sourceDir . (substr($sourceDir, -1) == DS ? "" : DS); + } else { + self::$includePath[$namespace] = $sourceDir . (substr($sourceDir, -1) == DS ? "" : DS); + } + } + + function loadClass($className) + { + var_dump(self::$includePath); die; + $className = ltrim($className, NS); + + foreach (self::$includePath as $path) { + if ($lastPos = strrpos($className, NS)) { + $namespace = substr($className, 0, $lastPos); + var_dump($namespace); + $className = substr($className, $lastPos + 1); + $subpath = str_replace(NS, DS, $namespace) . DS; + } + + + $filename = $path . $subpath . $className . ".php"; + var_dump($filename); + + if (file_exists($filename)) { + require $filename . ".php"; + return true; + } + } + + return false; + } + + /** + * Loads the given class or interface. + * + * @param string $className The name of the class to load. + * @return void + */ + public function loadClass2($className) + { + if (null === $this->_namespace || $this->_namespace.$this->_namespaceSeparator === substr($className, 0, strlen($this->_namespace.$this->_namespaceSeparator))) { + $fileName = ''; + $namespace = ''; + + if (false !== ($lastNsPos = strripos($className, $this->_namespaceSeparator))) { + $namespace = substr($className, 0, $lastNsPos); + $className = substr($className, $lastNsPos + 1); + $fileName = str_replace($this->_namespaceSeparator, DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR; + } + + $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; + + require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; + } + } +} \ No newline at end of file diff --git a/src/ProcessMaker/Util/Logger.php b/src/framework/Maveriks/Util/Logger.php similarity index 100% rename from src/ProcessMaker/Util/Logger.php rename to src/framework/Maveriks/Util/Logger.php diff --git a/src/ProcessMaker/WebApplication.php b/src/framework/Maveriks/WebApplication.php similarity index 100% rename from src/ProcessMaker/WebApplication.php rename to src/framework/Maveriks/WebApplication.php diff --git a/workflow/engine/src/ProcessMaker/Util/Common.php b/workflow/engine/src/ProcessMaker/Util/Common.php index bba02ef2c..6245c1e84 100644 --- a/workflow/engine/src/ProcessMaker/Util/Common.php +++ b/workflow/engine/src/ProcessMaker/Util/Common.php @@ -1,128 +1,6 @@ - * @param string $pattern pattern for native glob function - * @param int|string $flags any valid flag for glob function - * @param bool $onlyFiles to filter return array with only matched files, or all matched results - * @return array array containing the recursive glob results - * - * Example: - * - * Common::rglob("/example/path/*"); - * - * it will returns: - * - * Array - * ( - * [0] => /example/path/README.txt - * [1] => /example/path/composer.json - * [4] => /example/path/one/one_text.txt - * [6] => /example/path/two/two_text.txt - * [7] => /example/path/two/two_one/two_one_text.txt - * [8] => /example/path/two/two_one/build.json - * ) - * - * Example 2: - * - * Common::rglob("/example/path/*.json"); - * - * It will returns: - * - * Array - * ( - * [0] => /example/path/composer.json - * [1] => /example/path/two/two_one/build.json - * ) - */ - public static function rglob($pattern, $flags = 0, $onlyFiles = false) - { - $singlePattern = basename($pattern); - - if (strpos($singlePattern, "*") !== false) { - $path = rtrim(str_replace($singlePattern, "", $pattern), DIRECTORY_SEPARATOR); - } else { - $singlePattern = ""; - $path = $pattern; - } - - $files = glob("$path/$singlePattern", $flags); - $dirs = glob("$path/*", GLOB_MARK|GLOB_ONLYDIR|GLOB_NOSORT); - - foreach ($dirs as $dir) { - $files = array_merge($files, self::rglob("$dir/$singlePattern", $flags)); - } - - if ($onlyFiles) { - $files = array_filter($files, function($v) { return is_dir($v) ? false : true;}); - } - - return $files; - } - - /** - * Returns the last version given a pattern of file name - * - * @param string $pattern a valid pattern for glob(...) native function - * @param int $flag php flags for glob(...) native function - * @return int|string - * - * Example: - * - Given the following files inside a directory: - * /example/path/myApplication-v1.tar - * /example/path/myApplication-v2.tar - * /example/path/myApplication-v3.tar - * /example/path/myApplication-v5.tar - * /example/path/myApplication-v7.tar - * - * $lastVer = ProcessMaker\Util\Common::getLastVersion("/example/path/myApplication-*.tar"); - * - * It will returns: 7 - */ - public static function getLastVersion($pattern, $flag = 0) - { - $files = glob($pattern, $flag); - $maxVersion = 0; - - $pattern = str_replace("*", '([0-9\.]+)', basename($pattern)); - - foreach ($files as $file) { - $filename = basename($file); - - if (preg_match('/'.$pattern.'/', $filename, $match)) { - - if ($maxVersion < $match[1]) { - $maxVersion = $match[1]; - } - } - } - - return $maxVersion; - } - - public static function parseIniFile($filename) - { - $data = @parse_ini_file($filename, true); - $result = array(); - - if ($data === false) { - throw new \Exception("Error parsing ini file: $filename"); - } - - foreach ($data as $key => $value) { - if (strpos($key, ':') !== false) { - list($key, $subSection) = explode(':', $key); - $result[trim($key)][trim($subSection)] = $value; - } else { - $result[$key] = $value; - } - } - - return $result; - } } \ No newline at end of file diff --git a/workflow/engine/src/ProcessMaker/Util/Logger.php b/workflow/engine/src/ProcessMaker/Util/Logger.php new file mode 100644 index 000000000..2a51ecfcb --- /dev/null +++ b/workflow/engine/src/ProcessMaker/Util/Logger.php @@ -0,0 +1,14 @@ + + */ +class Logger extends \Maveriks\Util\Logger +{ +} + diff --git a/workflow/public_html/app.php b/workflow/public_html/app.php index 54c1ac6ab..0d6af0c40 100644 --- a/workflow/public_html/app.php +++ b/workflow/public_html/app.php @@ -30,13 +30,19 @@ try { ); } - /** @var Composer\Autoload\ClassLoader $loader */ - $loader = include $rootDir . "vendor" . DIRECTORY_SEPARATOR . "autoload.php"; - $loader->add("", $rootDir . 'src/'); - $loader->add("", $rootDir . 'workflow/engine/src/'); - $loader->add("", $rootDir . 'workflow/engine/classes/model/'); + require $rootDir . "framework/src/Maveriks/Util/ClassLoader.php"; - $app = new ProcessMaker\WebApplication(); + $loader = Maveriks\Util\ClassLoader::getInstance(); + $loader->add($rootDir . 'framework/src/', "Maveriks"); + $loader->add($rootDir . 'workflow/engine/src/', "ProcessMaker"); + $loader->add($rootDir . 'workflow/engine/src/'); + $loader->add($rootDir . 'workflow/engine/classes/model/'); + + // and vendors to autoloader + $loader->add($rootDir . 'vendor/luracast/restler/vendor', "Luracast"); + $loader->add($rootDir . 'vendor/bshaffer/oauth2-server-php/src/', "OAuth2"); + + $app = new Maveriks\WebApplication(); $app->setRootDir($rootDir); $app->setRequestUri($_SERVER['REQUEST_URI']); @@ -44,14 +50,20 @@ try { switch ($stat) { - case ProcessMaker\WebApplication::RUNNING_WORKFLOW: + case Maveriks\WebApplication::RUNNING_WORKFLOW: include "sysGeneric.php"; break; - case ProcessMaker\WebApplication::RUNNING_API: - $app->run(ProcessMaker\WebApplication::SERVICE_API); + + case Maveriks\WebApplication::RUNNING_API: + $app->run(Maveriks\WebApplication::SERVICE_API); break; } } catch (Exception $e) { - die($e->getMessage()); + $view = new Maveriks\Pattern\Mvc\PhtmlView($rootDir . "framework/src/templates/Exception.phtml"); + $view->set("message", $e->getMessage()); + $view->set("exception", $e); + + $response = new Maveriks\Http\Response($view->getOutput(), 503); + $response->send(); } diff --git a/workflow/public_html/sysGeneric.php b/workflow/public_html/sysGeneric.php index fbda842a4..a1f13cf1f 100755 --- a/workflow/public_html/sysGeneric.php +++ b/workflow/public_html/sysGeneric.php @@ -274,787 +274,768 @@ define( 'PML_UPLOAD_URL', PML_SERVER . '/syspmLibrary/en/green/services/uploadPr define( 'PML_DOWNLOAD_URL', PML_SERVER . '/syspmLibrary/en/green/services/download' ); -try { - //Bootstrap::initVendors(); - $config = Bootstrap::getSystemConfiguration(); +$config = Bootstrap::getSystemConfiguration(); - // starting session - if (isset($config['session.gc_maxlifetime'])) { - $timelife = $config['session.gc_maxlifetime']; - } else { - $timelife = ini_get('session.gc_maxlifetime'); - } - if (is_null($timelife)) { - $timelife = 1440; - } - ini_set('session.gc_maxlifetime', $timelife); - if (preg_match("/msie/i", $_SERVER ['HTTP_USER_AGENT']) != 1 || $config['ie_cookie_lifetime'] == 1) { - ini_set('session.cookie_lifetime', $timelife); - } - //session_start(); +// starting session +if (isset($config['session.gc_maxlifetime'])) { + $timelife = $config['session.gc_maxlifetime']; +} else { + $timelife = ini_get('session.gc_maxlifetime'); +} +if (is_null($timelife)) { + $timelife = 1440; +} +ini_set('session.gc_maxlifetime', $timelife); +if (preg_match("/msie/i", $_SERVER ['HTTP_USER_AGENT']) != 1 || $config['ie_cookie_lifetime'] == 1) { + ini_set('session.cookie_lifetime', $timelife); +} +//session_start(); - $e_all = defined( 'E_DEPRECATED' ) ? E_ALL & ~ E_DEPRECATED : E_ALL; - $e_all = defined( 'E_STRICT' ) ? $e_all & ~ E_STRICT : $e_all; - $e_all = $config['debug'] ? $e_all : $e_all & ~ E_NOTICE; +$e_all = defined( 'E_DEPRECATED' ) ? E_ALL & ~ E_DEPRECATED : E_ALL; +$e_all = defined( 'E_STRICT' ) ? $e_all & ~ E_STRICT : $e_all; +$e_all = $config['debug'] ? $e_all : $e_all & ~ E_NOTICE; - // Do not change any of these settings directly, use env.ini instead - ini_set( 'display_errors', $config['debug'] ); - ini_set( 'error_reporting', $e_all ); - ini_set( 'short_open_tag', 'On' ); - ini_set( 'default_charset', "UTF-8" ); - ini_set( 'memory_limit', $config['memory_limit'] ); - ini_set( 'soap.wsdl_cache_enabled', $config['wsdl_cache'] ); - ini_set( 'date.timezone', $config['time_zone'] ); +// Do not change any of these settings directly, use env.ini instead +ini_set( 'display_errors', $config['debug'] ); +ini_set( 'error_reporting', $e_all ); +ini_set( 'short_open_tag', 'On' ); +ini_set( 'default_charset', "UTF-8" ); +ini_set( 'memory_limit', $config['memory_limit'] ); +ini_set( 'soap.wsdl_cache_enabled', $config['wsdl_cache'] ); +ini_set( 'date.timezone', $config['time_zone'] ); - define( 'DEBUG_SQL_LOG', $config['debug_sql'] ); - define( 'DEBUG_TIME_LOG', $config['debug_time'] ); - define( 'DEBUG_CALENDAR_LOG', $config['debug_calendar'] ); - define( 'MEMCACHED_ENABLED', $config['memcached'] ); - define( 'MEMCACHED_SERVER', $config['memcached_server'] ); - define( 'TIME_ZONE', $config['time_zone'] ); +define( 'DEBUG_SQL_LOG', $config['debug_sql'] ); +define( 'DEBUG_TIME_LOG', $config['debug_time'] ); +define( 'DEBUG_CALENDAR_LOG', $config['debug_calendar'] ); +define( 'MEMCACHED_ENABLED', $config['memcached'] ); +define( 'MEMCACHED_SERVER', $config['memcached_server'] ); +define( 'TIME_ZONE', $config['time_zone'] ); - // IIS Compatibility, SERVER_ADDR doesn't exist on that env, so we need to define it. - $_SERVER['SERVER_ADDR'] = isset( $_SERVER['SERVER_ADDR'] ) ? $_SERVER['SERVER_ADDR'] : $_SERVER['SERVER_NAME']; +// IIS Compatibility, SERVER_ADDR doesn't exist on that env, so we need to define it. +$_SERVER['SERVER_ADDR'] = isset( $_SERVER['SERVER_ADDR'] ) ? $_SERVER['SERVER_ADDR'] : $_SERVER['SERVER_NAME']; - //to do: make different environments. sys +//to do: make different environments. sys - //check if it is a installation instance - if (! defined( 'PATH_C' )) { - // is a intallation instance, so we need to define PATH_C and PATH_LANGUAGECONT constants temporarily - define( 'PATH_C', (rtrim( Bootstrap::sys_get_temp_dir(), PATH_SEP ) . PATH_SEP) ); - define( 'PATH_LANGUAGECONT', PATH_HOME . 'engine/content/languages/' ); - } +//check if it is a installation instance +if (! defined( 'PATH_C' )) { + // is a intallation instance, so we need to define PATH_C and PATH_LANGUAGECONT constants temporarily + define( 'PATH_C', (rtrim( Bootstrap::sys_get_temp_dir(), PATH_SEP ) . PATH_SEP) ); + define( 'PATH_LANGUAGECONT', PATH_HOME . 'engine/content/languages/' ); +} - //Call Gulliver Classes - Bootstrap::LoadThirdParty("smarty/libs", "Smarty.class"); +//Call Gulliver Classes +Bootstrap::LoadThirdParty("smarty/libs", "Smarty.class"); - //Loading the autoloader libraries feature - spl_autoload_register(array("Bootstrap", "autoloadClass")); +//Loading the autoloader libraries feature +spl_autoload_register(array("Bootstrap", "autoloadClass")); - Bootstrap::registerClass("G", PATH_GULLIVER . "class.g.php"); - Bootstrap::registerClass("System", PATH_HOME . "engine/classes/class.system.php"); +Bootstrap::registerClass("G", PATH_GULLIVER . "class.g.php"); +Bootstrap::registerClass("System", PATH_HOME . "engine/classes/class.system.php"); - $skinPathErrors = G::skinGetPathToSrcByVirtualUri("errors", $config); - $skinPathUpdate = G::skinGetPathToSrcByVirtualUri("update", $config); +$skinPathErrors = G::skinGetPathToSrcByVirtualUri("errors", $config); +$skinPathUpdate = G::skinGetPathToSrcByVirtualUri("update", $config); - // defining Virtual URLs - $virtualURITable = array (); - $virtualURITable['/plugin/(*)'] = 'plugin'; - $virtualURITable['/(sys*)/(*.js)'] = 'jsMethod'; - $virtualURITable['/js/(*)'] = PATH_GULLIVER_HOME . 'js/'; - $virtualURITable['/jscore/(*)'] = PATH_CORE . 'js/'; +// defining Virtual URLs +$virtualURITable = array (); +$virtualURITable['/plugin/(*)'] = 'plugin'; +$virtualURITable['/(sys*)/(*.js)'] = 'jsMethod'; +$virtualURITable['/js/(*)'] = PATH_GULLIVER_HOME . 'js/'; +$virtualURITable['/jscore/(*)'] = PATH_CORE . 'js/'; - if (defined( 'PATH_C' )) { - $virtualURITable['/jsform/(*.js)'] = PATH_C . 'xmlform/'; - $virtualURITable['/extjs/(*)'] = PATH_C . 'ExtJs/'; - } +if (defined( 'PATH_C' )) { + $virtualURITable['/jsform/(*.js)'] = PATH_C . 'xmlform/'; + $virtualURITable['/extjs/(*)'] = PATH_C . 'ExtJs/'; +} - $virtualURITable['/htmlarea/(*)'] = PATH_THIRDPARTY . 'htmlarea/'; - //$virtualURITable['/sys[a-zA-Z][a-zA-Z0-9]{0,}()/'] = 'sysNamed'; - $virtualURITable['/(sys*)'] = FALSE; - $virtualURITable["/errors/(*)"] = ($skinPathErrors != "")? $skinPathErrors : PATH_GULLIVER_HOME . "methods" . PATH_SEP . "errors" . PATH_SEP; - $virtualURITable['/gulliver/(*)'] = PATH_GULLIVER_HOME . 'methods/'; - $virtualURITable['/controls/(*)'] = PATH_GULLIVER_HOME . 'methods/controls/'; - $virtualURITable['/html2ps_pdf/(*)'] = PATH_THIRDPARTY . 'html2ps_pdf/'; - //$virtualURITable['/images/'] = 'errorFile'; - //$virtualURITable['/skins/'] = 'errorFile'; - //$virtualURITable['/files/'] = 'errorFile'; - $virtualURITable['/(*)api/(*)'] = 'api-service'; - $virtualURITable["/update/(*)"] = ($skinPathUpdate != "")? $skinPathUpdate : PATH_GULLIVER_HOME . "methods" . PATH_SEP . "update" . PATH_SEP; - //$virtualURITable['/(*)'] = PATH_HTML; - $virtualURITable['/css/(*)'] = PATH_HTML . 'css/'; //ugly - $virtualURITable['/skin/(*)'] = PATH_HTML; - $virtualURITable['/skins/(*)'] = PATH_HTML . 'skins/'; //ugly - $virtualURITable['/images/(*)'] = PATH_HTML . 'images/'; //ugly - $virtualURITable['/[a-zA-Z][a-zA-Z0-9]{0,}/'] = 'errorFile'; +$virtualURITable['/htmlarea/(*)'] = PATH_THIRDPARTY . 'htmlarea/'; +//$virtualURITable['/sys[a-zA-Z][a-zA-Z0-9]{0,}()/'] = 'sysNamed'; +$virtualURITable['/(sys*)'] = FALSE; +$virtualURITable["/errors/(*)"] = ($skinPathErrors != "")? $skinPathErrors : PATH_GULLIVER_HOME . "methods" . PATH_SEP . "errors" . PATH_SEP; +$virtualURITable['/gulliver/(*)'] = PATH_GULLIVER_HOME . 'methods/'; +$virtualURITable['/controls/(*)'] = PATH_GULLIVER_HOME . 'methods/controls/'; +$virtualURITable['/html2ps_pdf/(*)'] = PATH_THIRDPARTY . 'html2ps_pdf/'; +//$virtualURITable['/images/'] = 'errorFile'; +//$virtualURITable['/skins/'] = 'errorFile'; +//$virtualURITable['/files/'] = 'errorFile'; +$virtualURITable['/(*)api/(*)'] = 'api-service'; +$virtualURITable["/update/(*)"] = ($skinPathUpdate != "")? $skinPathUpdate : PATH_GULLIVER_HOME . "methods" . PATH_SEP . "update" . PATH_SEP; +//$virtualURITable['/(*)'] = PATH_HTML; +$virtualURITable['/css/(*)'] = PATH_HTML . 'css/'; //ugly +$virtualURITable['/skin/(*)'] = PATH_HTML; +$virtualURITable['/skins/(*)'] = PATH_HTML . 'skins/'; //ugly +$virtualURITable['/images/(*)'] = PATH_HTML . 'images/'; //ugly +$virtualURITable['/[a-zA-Z][a-zA-Z0-9]{0,}/'] = 'errorFile'; - $isRestRequest = false; - // Verify if we need to redirect or stream the file, if G:VirtualURI returns true means we are going to redirect the page - if (Bootstrap::virtualURI( $_SERVER['REQUEST_URI'], $virtualURITable, $realPath )) { - // review if the file requested belongs to public_html plugin - if (substr( $realPath, 0, 6 ) == 'plugin') { - // Another way to get the path of Plugin public_html and stream the correspondent file, By JHL Jul 14, 08 - // TODO: $pathsQuery will be used? - $pathsQuery = ''; - // Get the query side - // Did we use this variable $pathsQuery for something?? - $forQuery = explode( "?", $realPath ); - if (isset( $forQuery[1] )) { - $pathsQuery = $forQuery[1]; - } - - //Get that path in array - $paths = explode( PATH_SEP, $forQuery[0] ); - //remove the "plugin" word from - $paths[0] = substr( $paths[0], 6 ); - //Get the Plugin Folder, always the first element - $pluginFolder = array_shift( $paths ); - //The other parts are the realpath into public_html (no matter how many elements) - $filePath = implode( PATH_SEP, $paths ); - $pluginFilename = PATH_PLUGINS . $pluginFolder . PATH_SEP . 'public_html' . PATH_SEP . $filePath; - - if (file_exists( $pluginFilename )) { - //NewRelic Snippet - By JHL - transactionLog($pluginFilename); - - Bootstrap::streamFile( $pluginFilename, false, '', true ); - } - die(); +$isRestRequest = false; +// Verify if we need to redirect or stream the file, if G:VirtualURI returns true means we are going to redirect the page +if (Bootstrap::virtualURI( $_SERVER['REQUEST_URI'], $virtualURITable, $realPath )) { + // review if the file requested belongs to public_html plugin + if (substr( $realPath, 0, 6 ) == 'plugin') { + // Another way to get the path of Plugin public_html and stream the correspondent file, By JHL Jul 14, 08 + // TODO: $pathsQuery will be used? + $pathsQuery = ''; + // Get the query side + // Did we use this variable $pathsQuery for something?? + $forQuery = explode( "?", $realPath ); + if (isset( $forQuery[1] )) { + $pathsQuery = $forQuery[1]; } - $requestUriArray = explode( "/", $_SERVER['REQUEST_URI'] ); + //Get that path in array + $paths = explode( PATH_SEP, $forQuery[0] ); + //remove the "plugin" word from + $paths[0] = substr( $paths[0], 6 ); + //Get the Plugin Folder, always the first element + $pluginFolder = array_shift( $paths ); + //The other parts are the realpath into public_html (no matter how many elements) + $filePath = implode( PATH_SEP, $paths ); + $pluginFilename = PATH_PLUGINS . $pluginFolder . PATH_SEP . 'public_html' . PATH_SEP . $filePath; - if ((isset( $requestUriArray[1] )) && ($requestUriArray[1] == 'skin')) { - // This will allow to public images of Custom Skins, By JHL Feb 28, 11 - $pathsQuery = ""; - // Get the query side - // This way we remove garbage - $forQuery = explode( "?", $realPath ); - if (isset( $forQuery[1] )) { - $pathsQuery = $forQuery[1]; - } + if (file_exists( $pluginFilename )) { + //NewRelic Snippet - By JHL + transactionLog($pluginFilename); - //Get that path in array - $paths = explode( PATH_SEP, $forQuery[0] ); - $url = (preg_match("/^(.*)\?.*$/", $_SERVER["REQUEST_URI"], $arrayMatch))? $arrayMatch[1] : $_SERVER["REQUEST_URI"]; - - $fileToBeStreamed = str_replace("/skin/", PATH_CUSTOM_SKINS, $url); - - if (file_exists( $fileToBeStreamed )) { - //NewRelic Snippet - By JHL - transactionLog($fileToBeStreamed); - - Bootstrap::streamFile( $fileToBeStreamed ); - } - die(); + Bootstrap::streamFile( $pluginFilename, false, '', true ); } - - switch ($realPath) { - case 'jsMethod': - Bootstrap::parseURI( getenv( "REQUEST_URI" ) ); - $filename = PATH_METHODS . SYS_COLLECTION . '/' . SYS_TARGET . '.js'; - //NewRelic Snippet - By JHL - transactionLog($filename); - Bootstrap::streamFile( $filename ); - die(); - break; - case 'errorFile': - header( "location: /errors/error404.php?url=" . urlencode( $_SERVER['REQUEST_URI'] ) ); - if (DEBUG_TIME_LOG) - Bootstrap::logTimeByPage(); //log this page - die(); - break; - default: - //Process files loaded with tag head in HTML - if (substr( $realPath, 0, 11 ) == 'api-service') { - $isRestRequest = true; - } else { - $realPath = explode( '?', $realPath ); - $realPath[0] .= strpos( basename( $realPath[0] ), '.' ) === false ? '.php' : ''; - //NewRelic Snippet - By JHL - transactionLog($realPath[0]); - - Bootstrap::streamFile( $realPath[0] ); - die(); - } - } - } //virtual URI parser - - // the request correspond to valid php page, now parse the URI - Bootstrap::parseURI( getenv( "REQUEST_URI" ), $isRestRequest ); - - // Bootstrap::mylog("sys_temp: ".SYS_TEMP); - if (Bootstrap::isPMUnderUpdating()) { - header( "location: /update/updating.php" ); - if (DEBUG_TIME_LOG) - Bootstrap::logTimeByPage(); die(); } - // verify if index.html exists - if (! file_exists( PATH_HTML . 'index.html' )) { // if not, create it from template - file_put_contents( PATH_HTML . 'index.html', Bootstrap::parseTemplate( PATH_TPL . 'index.html', array ('lang' => SYS_LANG,'skin' => SYS_SKIN - ) ) ); - } + $requestUriArray = explode( "/", $_SERVER['REQUEST_URI'] ); - define( 'SYS_URI', '/sys' . SYS_TEMP . '/' . SYS_LANG . '/' . SYS_SKIN . '/' ); - - // defining the serverConf singleton - if (defined( 'PATH_DATA' ) && file_exists( PATH_DATA )) { - //Instance Server Configuration Singleton - Bootstrap::LoadClass( 'serverConfiguration' ); - $oServerConf = & serverConf::getSingleton(); - } - - // Call more Classes - Bootstrap::registerClass('headPublisher', PATH_GULLIVER . "class.headPublisher.php"); - Bootstrap::registerClass('publisher', PATH_GULLIVER . "class.publisher.php"); - Bootstrap::registerClass('xmlform', PATH_GULLIVER . "class.xmlform.php"); - Bootstrap::registerClass('XmlForm_Field', PATH_GULLIVER . "class.xmlform.php"); - Bootstrap::registerClass('xmlformExtension', PATH_GULLIVER . "class.xmlformExtension.php"); - Bootstrap::registerClass('form', PATH_GULLIVER . "class.form.php"); - Bootstrap::registerClass('menu', PATH_GULLIVER . "class.menu.php"); - Bootstrap::registerClass('Xml_Document', PATH_GULLIVER . "class.xmlDocument.php"); - Bootstrap::registerClass('DBSession', PATH_GULLIVER . "class.dbsession.php"); - Bootstrap::registerClass('DBConnection', PATH_GULLIVER . "class.dbconnection.php"); - Bootstrap::registerClass('DBRecordset', PATH_GULLIVER . "class.dbrecordset.php"); - Bootstrap::registerClass('DBTable', PATH_GULLIVER . "class.dbtable.php"); - Bootstrap::registerClass('xmlMenu', PATH_GULLIVER . "class.xmlMenu.php"); - Bootstrap::registerClass('XmlForm_Field_FastSearch', PATH_GULLIVER . "class.xmlformExtension.php"); - Bootstrap::registerClass('XmlForm_Field_XmlMenu', PATH_GULLIVER . "class.xmlMenu.php"); - Bootstrap::registerClass('XmlForm_Field_HTML', PATH_GULLIVER . "class.dvEditor.php"); - Bootstrap::registerClass('XmlForm_Field_WYSIWYG_EDITOR', PATH_GULLIVER . "class.wysiwygEditor.php"); - Bootstrap::registerClass('Controller', PATH_GULLIVER . "class.controller.php"); - Bootstrap::registerClass('HttpProxyController', PATH_GULLIVER . "class.httpProxyController.php"); - Bootstrap::registerClass('templatePower', PATH_GULLIVER . "class.templatePower.php"); - Bootstrap::registerClass('XmlForm_Field_SimpleText', PATH_GULLIVER . "class.xmlformExtension.php"); - Bootstrap::registerClass('PmSessionHandler', PATH_GULLIVER_HOME . 'core/Session/PmSessionHandler.php'); - Bootstrap::registerClass('Groups', PATH_HOME . "engine/classes/class.groups.php"); - Bootstrap::registerClass('Tasks', PATH_HOME . "engine/classes/class.tasks.php"); - Bootstrap::registerClass('Calendar', PATH_HOME . "engine/classes/class.calendar.php"); - Bootstrap::registerClass('processMap', PATH_HOME . "engine/classes/class.processMap.php"); - - Bootstrap::registerSystemClasses(); - - Bootstrap::registerDir('src', PATH_HOME . 'engine/src/'); - Bootstrap::registerDir('model', PATH_CORE . 'classes' . PATH_SEP . 'model'); - Bootstrap::registerDir('rbac/model', PATH_RBAC_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'model'); - - require_once PATH_THIRDPARTY . '/pear/PEAR.php'; - - //Bootstrap::LoadSystem( 'pmException' ); - - // Create headPublisher singleton - //Bootstrap::LoadSystem( 'headPublisher' ); - $oHeadPublisher = & headPublisher::getSingleton(); - - // Installer, redirect to install if we don't have a valid shared data folder - if (! defined( 'PATH_DATA' ) || ! file_exists( PATH_DATA )) { - // new installer, extjs based - define( 'PATH_DATA', PATH_C ); - //NewRelic Snippet - By JHL - transactionLog(PATH_CONTROLLERS.'installer.php'); - require_once (PATH_CONTROLLERS . 'installer.php'); - $controller = 'Installer'; - - // if the method name is empty set default to index method - if (strpos( SYS_TARGET, '/' ) !== false) { - list ($controller, $controllerAction) = explode( '/', SYS_TARGET ); - } else { - $controllerAction = SYS_TARGET; + if ((isset( $requestUriArray[1] )) && ($requestUriArray[1] == 'skin')) { + // This will allow to public images of Custom Skins, By JHL Feb 28, 11 + $pathsQuery = ""; + // Get the query side + // This way we remove garbage + $forQuery = explode( "?", $realPath ); + if (isset( $forQuery[1] )) { + $pathsQuery = $forQuery[1]; } - $controllerAction = ($controllerAction != '' && $controllerAction != 'login') ? $controllerAction : 'index'; + //Get that path in array + $paths = explode( PATH_SEP, $forQuery[0] ); + $url = (preg_match("/^(.*)\?.*$/", $_SERVER["REQUEST_URI"], $arrayMatch))? $arrayMatch[1] : $_SERVER["REQUEST_URI"]; - // create the installer controller and call its method - if (is_callable( Array ('Installer',$controllerAction - ) )) { - $installer = new $controller(); - $installer->setHttpRequestData( $_REQUEST ); + $fileToBeStreamed = str_replace("/skin/", PATH_CUSTOM_SKINS, $url); + + if (file_exists( $fileToBeStreamed )) { //NewRelic Snippet - By JHL - transactionLog($controllerAction); + transactionLog($fileToBeStreamed); - $installer->call( $controllerAction ); - } else { - $_SESSION['phpFileNotFound'] = $_SERVER['REQUEST_URI']; + Bootstrap::streamFile( $fileToBeStreamed ); + } + die(); + } + + switch ($realPath) { + case 'jsMethod': + Bootstrap::parseURI( getenv( "REQUEST_URI" ) ); + $filename = PATH_METHODS . SYS_COLLECTION . '/' . SYS_TARGET . '.js'; + //NewRelic Snippet - By JHL + transactionLog($filename); + Bootstrap::streamFile( $filename ); + die(); + break; + case 'errorFile': header( "location: /errors/error404.php?url=" . urlencode( $_SERVER['REQUEST_URI'] ) ); - } - die(); - } - - // Load Language Translation - Bootstrap::LoadTranslationObject( defined( 'SYS_LANG' ) ? SYS_LANG : "en" ); - - // look for a disabled workspace - if ($oServerConf->isWSDisabled( SYS_TEMP )) { - $aMessage['MESSAGE'] = Bootstrap::LoadTranslation( 'ID_DISB_WORKSPACE' ); - $G_PUBLISH = new Publisher(); - $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', $aMessage ); - Bootstrap::RenderPage( 'publish' ); - die(); - } - - // database and workspace definition - // if SYS_TEMP exists, the URL has a workspace, now we need to verify if exists their db.php file - if (defined( 'SYS_TEMP' ) && SYS_TEMP != '') { - //this is the default, the workspace db.php file is in /shared/workflow/sites/SYS_SYS - if (file_exists( PATH_DB . SYS_TEMP . '/db.php' )) { - require_once (PATH_DB . SYS_TEMP . '/db.php'); - define( 'SYS_SYS', SYS_TEMP ); - - // defining constant for workspace shared directory - define( 'PATH_WORKSPACE', PATH_DB . SYS_SYS . PATH_SEP ); - // including workspace shared classes -> particularlly for pmTables - set_include_path( get_include_path() . PATH_SEPARATOR . PATH_WORKSPACE ); - } else { - if (SYS_LANG != '' && SYS_SKIN != '') { - Bootstrap::SendTemporalMessage( 'ID_NOT_WORKSPACE', "error" ); - Bootstrap::header( 'location: /sys/' . SYS_LANG . '/' . SYS_SKIN . '/main/sysLogin?errno=2' ); - } else { - header('location: /errors/error404.php?url=' . urlencode($_SERVER['REQUEST_URI'])); - } - die(); - } - } else { //when we are in global pages, outside any valid workspace - if (SYS_TARGET === 'newSite') { - $phpFile = G::ExpandPath( 'methods' ) . SYS_COLLECTION . "/" . SYS_TARGET . '.php'; - //NewRelic Snippet - By JHL - transactionLog($phpFile); - require_once ($phpFile); - die(); - } else { - if (SYS_TARGET == "dbInfo") { //Show dbInfo when no SYS_SYS - require_once (PATH_METHODS . "login/dbInfo.php"); - } else { - - if (substr( SYS_SKIN, 0, 2 ) === 'ux' && SYS_TARGET != 'sysLoginVerify') { // new ux sysLogin - extjs based form - require_once PATH_CONTROLLERS . 'main.php'; - $controllerClass = 'Main'; - $controllerAction = SYS_TARGET == 'sysLoginVerify' ? SYS_TARGET : 'sysLogin'; - //if the method exists - if (is_callable( Array ($controllerClass,$controllerAction - ) )) { - $controller = new $controllerClass(); - $controller->setHttpRequestData( $_REQUEST ); - $controller->call( $controllerAction ); - } - } else { // classic sysLogin interface - require_once (PATH_METHODS . "login/sysLogin.php"); - die(); - } - } if (DEBUG_TIME_LOG) Bootstrap::logTimeByPage(); //log this page die(); - } - } - - // PM Paths DATA - define( 'PATH_DATA_SITE', PATH_DATA . 'sites/' . SYS_SYS . '/' ); - define( 'PATH_DOCUMENT', PATH_DATA_SITE . 'files/' ); - define( 'PATH_DATA_MAILTEMPLATES', PATH_DATA_SITE . 'mailTemplates/' ); - define( 'PATH_DATA_PUBLIC', PATH_DATA_SITE . 'public/' ); - define( 'PATH_DATA_REPORTS', PATH_DATA_SITE . 'reports/' ); - define( 'PATH_DYNAFORM', PATH_DATA_SITE . 'xmlForms/' ); - define( 'PATH_IMAGES_ENVIRONMENT_FILES', PATH_DATA_SITE . 'usersFiles' . PATH_SEP ); - define( 'PATH_IMAGES_ENVIRONMENT_USERS', PATH_DATA_SITE . 'usersPhotographies' . PATH_SEP ); - define( 'SERVER_NAME', $_SERVER['SERVER_NAME'] ); - define( 'SERVER_PORT', $_SERVER['SERVER_PORT'] ); - - - - // create memcached singleton - Bootstrap::LoadClass( 'memcached' ); - $memcache = & PMmemcached::getSingleton( SYS_SYS ); - - // verify configuration for rest service - /*if ($isRestRequest) { - // disable until confirm that rest is enabled & configured on rest-config.ini file - $isRestRequest = false; - $confFile = ''; - $restApiClassPath = ''; - - // try load and getting rest configuration - if (file_exists( PATH_DATA_SITE . 'rest-config.ini' )) { - $confFile = PATH_DATA_SITE . 'rest-config.ini'; - $restApiClassPath = PATH_DATA_SITE; - } elseif (file_exists( PATH_CONFIG . 'rest-config.ini' )) { - $confFile = PATH_CONFIG . 'rest-config.ini'; - } - if (! empty( $confFile ) && $restConfig = @parse_ini_file( $confFile, true )) { - if (array_key_exists( 'enable_service', $restConfig )) { - if ($restConfig['enable_service'] == 'true' || $restConfig['enable_service'] == '1') { - $isRestRequest = true; // rest service enabled - } - } - } - }*/ - - // load Plugins base class - Bootstrap::LoadClass( 'plugin' ); - - //here we are loading all plugins registered - //the singleton has a list of enabled plugins - $sSerializedFile = PATH_DATA_SITE . 'plugin.singleton'; - $oPluginRegistry = & PMPluginRegistry::getSingleton(); - - if (file_exists( $sSerializedFile )) { - $oPluginRegistry->unSerializeInstance( file_get_contents( $sSerializedFile ) ); - $attributes = $oPluginRegistry->getAttributes(); - Bootstrap::LoadTranslationPlugins( defined( 'SYS_LANG' ) ? SYS_LANG : "en" , $attributes); - } - - // setup propel definitions and logging - //changed to autoloader - //require_once ("propel/Propel.php"); - //require_once ("creole/Creole.php"); - - list($host, $port) = strpos(DB_HOST, ':') !== false ? explode(':', DB_HOST) : array(DB_HOST, ''); - $port = empty($port) ? '' : ";port=$port"; - $handler = new PmSessionHandler(DB_USER, DB_PASS, DB_ADAPTER.":host=$host;dbname=".DB_NAME.$port); - - session_start(); - - if (defined( 'DEBUG_SQL_LOG' ) && DEBUG_SQL_LOG) { - define( 'PM_PID', mt_rand( 1, 999999 ) ); - require_once 'Log.php'; - - // register debug connection decorator driver - Creole::registerDriver( '*', 'creole.contrib.DebugConnection' ); - - // initialize Propel with converted config file - Propel::init( PATH_CORE . "config/databases.php" ); - - // unified log file for all databases - $logFile = PATH_DATA . 'log' . PATH_SEP . 'propel.log'; - $logger = Log::singleton( 'file', $logFile, 'wf ' . SYS_SYS, null, PEAR_LOG_INFO ); - Propel::setLogger( $logger ); - // log file for workflow database - $con = Propel::getConnection( 'workflow' ); - if ($con instanceof DebugConnection) { - $con->setLogger( $logger ); - } - // log file for rbac database - $con = Propel::getConnection( 'rbac' ); - - if ($con instanceof DebugConnection) { - $con->setLogger( $logger ); - } - - // log file for report database - $con = Propel::getConnection( 'rp' ); - if ($con instanceof DebugConnection) { - $con->setLogger( $logger ); - } - } else { - Propel::init( PATH_CORE . "config/databases.php" ); - } - - Creole::registerDriver( 'dbarray', 'creole.contrib.DBArrayConnection' ); - - // Session Initializations - ini_set( 'session.auto_start', '1' ); - - // The register_globals feature has been DEPRECATED as of PHP 5.3.0. default value Off. - // ini_set( 'register_globals', 'Off' ); - //session_start(); - ob_start(); - - // Rebuild the base Workflow translations if not exists - if (! is_file( PATH_LANGUAGECONT . 'translation.en' )) { - require_once ("classes/model/Translation.php"); - $fields = Translation::generateFileTranslation( 'en' ); - } - - // TODO: Verify if the language set into url is defined in translations env. - if (SYS_LANG != 'en' && ! is_file( PATH_LANGUAGECONT . 'translation.' . SYS_LANG )) { - require_once ("classes/model/Translation.php"); - $fields = Translation::generateFileTranslation( SYS_LANG ); - } - - // Setup plugins - $oPluginRegistry->setupPlugins(); //get and setup enabled plugins - $avoidChangedWorkspaceValidation = false; - - // Load custom Classes and Model from Plugins. - Bootstrap::LoadAllPluginModelClasses(); - - // jump to php file in methods directory - $collectionPlugin = ''; - if ($oPluginRegistry->isRegisteredFolder( SYS_COLLECTION )) { - $phpFile = PATH_PLUGINS . SYS_COLLECTION . PATH_SEP . SYS_TARGET . '.php'; - $targetPlugin = explode( '/', SYS_TARGET ); - $collectionPlugin = $targetPlugin[0]; - $avoidChangedWorkspaceValidation = true; - } else { - $phpFile = Bootstrap::ExpandPath( 'methods' ) . SYS_COLLECTION . PATH_SEP . SYS_TARGET . '.php'; - } - - // services is a special folder, - if (SYS_COLLECTION == 'services') { - $avoidChangedWorkspaceValidation = true; - $targetPlugin = explode( '/', SYS_TARGET ); - - if ($targetPlugin[0] == 'webdav') { - $phpFile = Bootstrap::ExpandPath( 'methods' ) . SYS_COLLECTION . PATH_SEP . 'webdav.php'; - } - } - - if (SYS_COLLECTION == 'login' && SYS_TARGET == 'login') { - $avoidChangedWorkspaceValidation = true; - } - - $bWE = false; - $isControllerCall = false; - $isPluginController = false; - - if (substr( SYS_COLLECTION, 0, 8 ) === 'gulliver') { - $phpFile = PATH_GULLIVER_HOME . 'methods/' . substr( SYS_COLLECTION, 8 ) . SYS_TARGET . '.php'; - } else { - //when the file is part of the public directory of any PROCESS, this a ProcessMaker feature - if (preg_match( '/^[0-9][[:alnum:]]+$/', SYS_COLLECTION ) == 1) { //the pattern is /sysSYS/LANG/SKIN/PRO_UID/file - $auxPart = explode( '/', $_SERVER['REQUEST_URI'] ); - $aAux = explode( '?', $auxPart[count( $auxPart ) - 1] ); - //$extPart = explode ( '.' , $auxPart[ count($auxPart)-1] ); - $extPart = explode( '.', $aAux[0] ); - $queryPart = isset( $aAux[1] ) ? $aAux[1] : ""; - $extension = $extPart[count( $extPart ) - 1]; - $phpFile = PATH_DATA_SITE . 'public' . PATH_SEP . SYS_COLLECTION . PATH_SEP . urldecode( $auxPart[count( $auxPart ) - 1] ); - $aAux = explode( '?', $phpFile ); - $phpFile = $aAux[0]; - - if ($extension != 'php') { + break; + default: + //Process files loaded with tag head in HTML + if (substr( $realPath, 0, 11 ) == 'api-service') { + $isRestRequest = true; + } else { + $realPath = explode( '?', $realPath ); + $realPath[0] .= strpos( basename( $realPath[0] ), '.' ) === false ? '.php' : ''; //NewRelic Snippet - By JHL - transactionLog($phpFile); - Bootstrap::streamFile( $phpFile ); + transactionLog($realPath[0]); + + Bootstrap::streamFile( $realPath[0] ); die(); } + } +} //virtual URI parser - $avoidChangedWorkspaceValidation = true; - $bWE = true; - //$phpFile = PATH_DATA_SITE . 'public' . PATH_SEP . SYS_COLLECTION . PATH_SEP . $auxPart[ count($auxPart)-1]; - } +// the request correspond to valid php page, now parse the URI +Bootstrap::parseURI( getenv( "REQUEST_URI" ), $isRestRequest ); - //erik: verify if it is a Controller Class or httpProxyController Class - if (is_file( PATH_CONTROLLERS . SYS_COLLECTION . '.php' )) { - Bootstrap::LoadSystem( 'controller' ); - require_once PATH_CONTROLLERS . SYS_COLLECTION . '.php'; - $controllerClass = SYS_COLLECTION; - //if the method name is empty set default to index method - $controllerAction = SYS_TARGET != '' ? SYS_TARGET : 'index'; - //if the method exists - if (is_callable( Array ($controllerClass,$controllerAction ) )) { - $isControllerCall = true; - } +// Bootstrap::mylog("sys_temp: ".SYS_TEMP); +if (Bootstrap::isPMUnderUpdating()) { + header( "location: /update/updating.php" ); + if (DEBUG_TIME_LOG) + Bootstrap::logTimeByPage(); + die(); +} - if (substr(SYS_SKIN, 0, 2) != "ux" && $controllerClass == "main") { - $isControllerCall = false; - } - } +// verify if index.html exists +if (! file_exists( PATH_HTML . 'index.html' )) { // if not, create it from template + file_put_contents( PATH_HTML . 'index.html', Bootstrap::parseTemplate( PATH_TPL . 'index.html', array ('lang' => SYS_LANG,'skin' => SYS_SKIN + ) ) ); +} - if (is_dir(PATH_PLUGINS . SYS_COLLECTION) && $oPluginRegistry->isRegisteredFolder(SYS_COLLECTION)) { - $pluginName = SYS_COLLECTION; - $pluginResourceRequest = explode('/', rtrim(SYS_TARGET, '/')); - $isPluginController = true; +define( 'SYS_URI', '/sys' . SYS_TEMP . '/' . SYS_LANG . '/' . SYS_SKIN . '/' ); - if ($pluginResourceRequest > 0) { - $controllerClass = $pluginResourceRequest[0]; +// defining the serverConf singleton +if (defined( 'PATH_DATA' ) && file_exists( PATH_DATA )) { + //Instance Server Configuration Singleton + Bootstrap::LoadClass( 'serverConfiguration' ); + $oServerConf = & serverConf::getSingleton(); +} - if (count($pluginResourceRequest) == 1) { - $controllerAction = 'index'; - } else { - $controllerAction = $pluginResourceRequest[1]; - } - } +// Call more Classes +Bootstrap::registerClass('headPublisher', PATH_GULLIVER . "class.headPublisher.php"); +Bootstrap::registerClass('publisher', PATH_GULLIVER . "class.publisher.php"); +Bootstrap::registerClass('xmlform', PATH_GULLIVER . "class.xmlform.php"); +Bootstrap::registerClass('XmlForm_Field', PATH_GULLIVER . "class.xmlform.php"); +Bootstrap::registerClass('xmlformExtension', PATH_GULLIVER . "class.xmlformExtension.php"); +Bootstrap::registerClass('form', PATH_GULLIVER . "class.form.php"); +Bootstrap::registerClass('menu', PATH_GULLIVER . "class.menu.php"); +Bootstrap::registerClass('Xml_Document', PATH_GULLIVER . "class.xmlDocument.php"); +Bootstrap::registerClass('DBSession', PATH_GULLIVER . "class.dbsession.php"); +Bootstrap::registerClass('DBConnection', PATH_GULLIVER . "class.dbconnection.php"); +Bootstrap::registerClass('DBRecordset', PATH_GULLIVER . "class.dbrecordset.php"); +Bootstrap::registerClass('DBTable', PATH_GULLIVER . "class.dbtable.php"); +Bootstrap::registerClass('xmlMenu', PATH_GULLIVER . "class.xmlMenu.php"); +Bootstrap::registerClass('XmlForm_Field_FastSearch', PATH_GULLIVER . "class.xmlformExtension.php"); +Bootstrap::registerClass('XmlForm_Field_XmlMenu', PATH_GULLIVER . "class.xmlMenu.php"); +Bootstrap::registerClass('XmlForm_Field_HTML', PATH_GULLIVER . "class.dvEditor.php"); +Bootstrap::registerClass('XmlForm_Field_WYSIWYG_EDITOR', PATH_GULLIVER . "class.wysiwygEditor.php"); +Bootstrap::registerClass('Controller', PATH_GULLIVER . "class.controller.php"); +Bootstrap::registerClass('HttpProxyController', PATH_GULLIVER . "class.httpProxyController.php"); +Bootstrap::registerClass('templatePower', PATH_GULLIVER . "class.templatePower.php"); +Bootstrap::registerClass('XmlForm_Field_SimpleText', PATH_GULLIVER . "class.xmlformExtension.php"); +Bootstrap::registerClass('PmSessionHandler', PATH_GULLIVER_HOME . 'core/Session/PmSessionHandler.php'); +Bootstrap::registerClass('Groups', PATH_HOME . "engine/classes/class.groups.php"); +Bootstrap::registerClass('Tasks', PATH_HOME . "engine/classes/class.tasks.php"); +Bootstrap::registerClass('Calendar', PATH_HOME . "engine/classes/class.calendar.php"); +Bootstrap::registerClass('processMap', PATH_HOME . "engine/classes/class.processMap.php"); - $pluginControllerPath = PATH_PLUGINS . $pluginName . PATH_SEP . 'controllers' . PATH_SEP; +Bootstrap::registerSystemClasses(); - if (is_file($pluginControllerPath. $controllerClass . '.php')) { - require_once $pluginControllerPath. $controllerClass . '.php'; - } elseif (is_file($pluginControllerPath. ucfirst($controllerClass) . '.php')) { - $controllerClass = ucfirst($controllerClass); - require_once $pluginControllerPath. $controllerClass . '.php'; - } elseif (is_file($pluginControllerPath. ucfirst($controllerClass) . 'Controller.php')) { - $controllerClass = ucfirst($controllerClass) . 'Controller'; - require_once $pluginControllerPath. $controllerClass . '.php'; - } +Bootstrap::registerDir('src', PATH_HOME . 'engine/src/'); +Bootstrap::registerDir('model', PATH_CORE . 'classes' . PATH_SEP . 'model'); +Bootstrap::registerDir('rbac/model', PATH_RBAC_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'model'); - //if the method exists - if (is_callable(array($controllerClass, $controllerAction))) { - $isControllerCall = true; - } - } +require_once PATH_THIRDPARTY . '/pear/PEAR.php'; - if (! $isControllerCall && ! file_exists( $phpFile ) && ! $isRestRequest) { - $_SESSION['phpFileNotFound'] = $_SERVER['REQUEST_URI']; - header( "location: /errors/error404.php?url=" . urlencode( $_SERVER['REQUEST_URI'] ) ); - die(); - } +//Bootstrap::LoadSystem( 'pmException' ); + +// Create headPublisher singleton +//Bootstrap::LoadSystem( 'headPublisher' ); +$oHeadPublisher = & headPublisher::getSingleton(); + +// Installer, redirect to install if we don't have a valid shared data folder +if (! defined( 'PATH_DATA' ) || ! file_exists( PATH_DATA )) { + // new installer, extjs based + define( 'PATH_DATA', PATH_C ); + //NewRelic Snippet - By JHL + transactionLog(PATH_CONTROLLERS.'installer.php'); + require_once (PATH_CONTROLLERS . 'installer.php'); + $controller = 'Installer'; + + // if the method name is empty set default to index method + if (strpos( SYS_TARGET, '/' ) !== false) { + list ($controller, $controllerAction) = explode( '/', SYS_TARGET ); + } else { + $controllerAction = SYS_TARGET; } - //redirect to login, if user changed the workspace in the URL - if (! $avoidChangedWorkspaceValidation && isset( $_SESSION['WORKSPACE'] ) && $_SESSION['WORKSPACE'] != SYS_SYS) { - $_SESSION['WORKSPACE'] = SYS_SYS; - Bootstrap::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_SYSTEM', "error" ); - // verify if the current skin is a 'ux' variant - $urlPart = substr( SYS_SKIN, 0, 2 ) == 'ux' && SYS_SKIN != 'uxs' ? '/main/login' : '/login/login'; + $controllerAction = ($controllerAction != '' && $controllerAction != 'login') ? $controllerAction : 'index'; - header( 'Location: /sys' . SYS_SYS . '/' . SYS_LANG . '/' . SYS_SKIN . $urlPart ); + // create the installer controller and call its method + if (is_callable( Array ('Installer',$controllerAction + ) )) { + $installer = new $controller(); + $installer->setHttpRequestData( $_REQUEST ); + //NewRelic Snippet - By JHL + transactionLog($controllerAction); + + $installer->call( $controllerAction ); + } else { + $_SESSION['phpFileNotFound'] = $_SERVER['REQUEST_URI']; + header( "location: /errors/error404.php?url=" . urlencode( $_SERVER['REQUEST_URI'] ) ); + } + die(); +} + +// Load Language Translation +Bootstrap::LoadTranslationObject( defined( 'SYS_LANG' ) ? SYS_LANG : "en" ); + +// look for a disabled workspace +if ($oServerConf->isWSDisabled( SYS_TEMP )) { + $aMessage['MESSAGE'] = Bootstrap::LoadTranslation( 'ID_DISB_WORKSPACE' ); + $G_PUBLISH = new Publisher(); + $G_PUBLISH->AddContent( 'xmlform', 'xmlform', 'login/showMessage', '', $aMessage ); + Bootstrap::RenderPage( 'publish' ); + die(); +} + +// database and workspace definition +// if SYS_TEMP exists, the URL has a workspace, now we need to verify if exists their db.php file +if (defined( 'SYS_TEMP' ) && SYS_TEMP != '') { + //this is the default, the workspace db.php file is in /shared/workflow/sites/SYS_SYS + if (file_exists( PATH_DB . SYS_TEMP . '/db.php' )) { + require_once (PATH_DB . SYS_TEMP . '/db.php'); + define( 'SYS_SYS', SYS_TEMP ); + + // defining constant for workspace shared directory + define( 'PATH_WORKSPACE', PATH_DB . SYS_SYS . PATH_SEP ); + // including workspace shared classes -> particularlly for pmTables + set_include_path( get_include_path() . PATH_SEPARATOR . PATH_WORKSPACE ); + } else { + if (SYS_LANG != '' && SYS_SKIN != '') { + Bootstrap::SendTemporalMessage( 'ID_NOT_WORKSPACE', "error" ); + Bootstrap::header( 'location: /sys/' . SYS_LANG . '/' . SYS_SKIN . '/main/sysLogin?errno=2' ); + } else { + header('location: /errors/error404.php?url=' . urlencode($_SERVER['REQUEST_URI'])); + } die(); } - - // enable rbac - Bootstrap::LoadSystem( 'rbac' ); - $RBAC = &RBAC::getSingleton( PATH_DATA, session_id() ); - $RBAC->sSystem = 'PROCESSMAKER'; - - // define and send Headers for all pages - if (! defined( 'EXECUTE_BY_CRON' )) { - header( "Expires: " . gmdate( "D, d M Y H:i:s", mktime( 0, 0, 0, date( 'm' ), date( 'd' ) - 1, date( 'Y' ) ) ) . " GMT" ); - header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" ); - header( "Cache-Control: no-store, no-cache, must-revalidate" ); - header( "Cache-Control: post-check=0, pre-check=0", false ); - header( "Pragma: no-cache" ); - - // get the language direction from ServerConf - define( 'SYS_LANG_DIRECTION', $oServerConf->getLanDirection() ); - - if ((isset( $_SESSION['USER_LOGGED'] )) && (! (isset( $_GET['sid'] )))) { - if (preg_match("/msie/i", $_SERVER ['HTTP_USER_AGENT']) != 1 || $config['ie_cookie_lifetime'] == 1) { - if (PHP_VERSION < 5.2) { - setcookie(session_name(), session_id(), time() + $timelife, '/', '; HttpOnly'); - } else { - setcookie(session_name(), session_id(), time() + $timelife, '/', null, false, true); - } - } - $RBAC->initRBAC(); - //using optimization with memcache, the user data will be in memcache 8 hours, or until session id goes invalid - $memKey = 'rbacSession' . session_id(); - if (($RBAC->aUserInfo = $memcache->get( $memKey )) === false) { - $RBAC->loadUserRolePermission( $RBAC->sSystem, $_SESSION['USER_LOGGED'] ); - $memcache->set( $memKey, $RBAC->aUserInfo, PMmemcached::EIGHT_HOURS ); - } +} else { //when we are in global pages, outside any valid workspace + if (SYS_TARGET === 'newSite') { + $phpFile = G::ExpandPath( 'methods' ) . SYS_COLLECTION . "/" . SYS_TARGET . '.php'; + //NewRelic Snippet - By JHL + transactionLog($phpFile); + require_once ($phpFile); + die(); + } else { + if (SYS_TARGET == "dbInfo") { //Show dbInfo when no SYS_SYS + require_once (PATH_METHODS . "login/dbInfo.php"); } else { - // this is the blank list to allow execute scripts with no login (without session started) - $noLoginFiles = $noLoginFolders = array (); - $noLoginFiles[] = 'login'; - $noLoginFiles[] = 'authentication'; - $noLoginFiles[] = 'login_Ajax'; - $noLoginFiles[] = 'dbInfo'; - $noLoginFiles[] = 'sysLoginVerify'; - $noLoginFiles[] = 'processes_Ajax'; - $noLoginFiles[] = 'updateTranslation'; - $noLoginFiles[] = 'autoinstallProcesses'; - $noLoginFiles[] = 'autoinstallPlugins'; - $noLoginFiles[] = 'heartbeatStatus'; - $noLoginFiles[] = 'showLogoFile'; - $noLoginFiles[] = 'forgotPassword'; - $noLoginFiles[] = 'retrivePassword'; - $noLoginFiles[] = 'defaultAjaxDynaform'; - $noLoginFiles[] = 'dynaforms_checkDependentFields'; - $noLoginFiles[] = 'fields_Ajax'; - $noLoginFiles[] = 'appFolderAjax'; - $noLoginFiles[] = 'steps_Ajax'; - $noLoginFiles[] = 'proxyCasesList'; - $noLoginFiles[] = 'casesStartPage_Ajax'; - $noLoginFiles[] = 'appProxy'; - $noLoginFiles[] = 'cases_Ajax'; - $noLoginFiles[] = 'casesList_Ajax'; - $noLoginFiles[] = 'proxyReassignCasesList'; - $noLoginFiles[] = 'ajaxListener'; - $noLoginFiles[] = 'cases_Step'; - $noLoginFiles[] = 'cases_ShowOutputDocument'; - $noLoginFiles[] = 'cases_ShowDocument'; - $noLoginFiles[] = 'cases_CatchExecute'; - $noLoginFiles[] = 'cases_SaveData'; - $noLoginFiles[] = 'cases_Derivate'; - $noLoginFiles[] = 'cases_NextStep'; - $noLoginFiles[] = 'genericAjax'; - $noLoginFiles[] = 'casesSaveDataView'; - $noLoginFolders[] = 'services'; - $noLoginFolders[] = 'tracker'; - $noLoginFolders[] = 'installer'; - - // This sentence is used when you lost the Session - if (! in_array( SYS_TARGET, $noLoginFiles ) && ! in_array( SYS_COLLECTION, $noLoginFolders ) && $bWE != true && $collectionPlugin != 'services' && ! $isRestRequest) { - $bRedirect = true; - if (isset( $_GET['sid'] )) { - Bootstrap::LoadClass( 'sessions' ); - $oSessions = new Sessions(); - if ($aSession = $oSessions->verifySession( $_GET['sid'] )) { - require_once 'classes/model/Users.php'; - $oUser = new Users(); - $aUser = $oUser->load( $aSession['USR_UID'] ); - $_SESSION['USER_LOGGED'] = $aUser['USR_UID']; - $_SESSION['USR_USERNAME'] = $aUser['USR_USERNAME']; - $bRedirect = false; - if (preg_match("/msie/i", $_SERVER ['HTTP_USER_AGENT']) != 1 || $config['ie_cookie_lifetime'] == 1) { - if (PHP_VERSION < 5.2) { - setcookie(session_name(), session_id(), time() + $timelife, '/', '; HttpOnly'); - } else { - setcookie(session_name(), session_id(), time() + $timelife, '/', null, false, true); - } - } - $RBAC->initRBAC(); - $RBAC->loadUserRolePermission( $RBAC->sSystem, $_SESSION['USER_LOGGED'] ); - $memKey = 'rbacSession' . session_id(); - $memcache->set( $memKey, $RBAC->aUserInfo, PMmemcached::EIGHT_HOURS ); - } - } - - if ($bRedirect) { - if (substr( SYS_SKIN, 0, 2 ) == 'ux' && SYS_SKIN != 'uxs') { // verify if the current skin is a 'ux' variant - $loginUrl = 'main/login'; - } else if (strpos( $_SERVER['REQUEST_URI'], '/home' ) !== false) { //verify is it is using the uxs skin for simplified interface - $loginUrl = 'home/login'; - } else { - $loginUrl = 'login/login'; // just set up the classic login - } - - if (empty( $_POST )) { - header( 'location: ' . SYS_URI . $loginUrl . '?u=' . urlencode( $_SERVER['REQUEST_URI'] ) ); - - } else { - if ($isControllerCall) { - header( "HTTP/1.0 302 session lost in controller" ); - } else { - header( 'location: ' . SYS_URI . $loginUrl ); - } - } - die(); + if (substr( SYS_SKIN, 0, 2 ) === 'ux' && SYS_TARGET != 'sysLoginVerify') { // new ux sysLogin - extjs based form + require_once PATH_CONTROLLERS . 'main.php'; + $controllerClass = 'Main'; + $controllerAction = SYS_TARGET == 'sysLoginVerify' ? SYS_TARGET : 'sysLogin'; + //if the method exists + if (is_callable( Array ($controllerClass,$controllerAction + ) )) { + $controller = new $controllerClass(); + $controller->setHttpRequestData( $_REQUEST ); + $controller->call( $controllerAction ); } + } else { // classic sysLogin interface + require_once (PATH_METHODS . "login/sysLogin.php"); + die(); } } - $_SESSION['phpLastFileFound'] = $_SERVER['REQUEST_URI']; + if (DEBUG_TIME_LOG) + Bootstrap::logTimeByPage(); //log this page + die(); + } +} - /** - * New feature for Gulliver framework to support Controllers & HttpProxyController classes handling - * - * @author setHttpRequestData($_REQUEST);//NewRelic Snippet - By JHL - transactionLog($controllerAction); +// PM Paths DATA +define( 'PATH_DATA_SITE', PATH_DATA . 'sites/' . SYS_SYS . '/' ); +define( 'PATH_DOCUMENT', PATH_DATA_SITE . 'files/' ); +define( 'PATH_DATA_MAILTEMPLATES', PATH_DATA_SITE . 'mailTemplates/' ); +define( 'PATH_DATA_PUBLIC', PATH_DATA_SITE . 'public/' ); +define( 'PATH_DATA_REPORTS', PATH_DATA_SITE . 'reports/' ); +define( 'PATH_DYNAFORM', PATH_DATA_SITE . 'xmlForms/' ); +define( 'PATH_IMAGES_ENVIRONMENT_FILES', PATH_DATA_SITE . 'usersFiles' . PATH_SEP ); +define( 'PATH_IMAGES_ENVIRONMENT_USERS', PATH_DATA_SITE . 'usersPhotographies' . PATH_SEP ); +define( 'SERVER_NAME', $_SERVER['SERVER_NAME'] ); +define( 'SERVER_PORT', $_SERVER['SERVER_PORT'] ); - if ($isPluginController) { - $controller->setPluginName($pluginName); - $controller->setPluginHomeDir(PATH_PLUGINS . $pluginName . PATH_SEP); + + +// create memcached singleton +Bootstrap::LoadClass( 'memcached' ); +$memcache = & PMmemcached::getSingleton( SYS_SYS ); + +// verify configuration for rest service +/*if ($isRestRequest) { + // disable until confirm that rest is enabled & configured on rest-config.ini file + $isRestRequest = false; + $confFile = ''; + $restApiClassPath = ''; + + // try load and getting rest configuration + if (file_exists( PATH_DATA_SITE . 'rest-config.ini' )) { + $confFile = PATH_DATA_SITE . 'rest-config.ini'; + $restApiClassPath = PATH_DATA_SITE; + } elseif (file_exists( PATH_CONFIG . 'rest-config.ini' )) { + $confFile = PATH_CONFIG . 'rest-config.ini'; + } + if (! empty( $confFile ) && $restConfig = @parse_ini_file( $confFile, true )) { + if (array_key_exists( 'enable_service', $restConfig )) { + if ($restConfig['enable_service'] == 'true' || $restConfig['enable_service'] == '1') { + $isRestRequest = true; // rest service enabled } - - $controller->call($controllerAction); - } elseif ($isRestRequest) { - $restConfig = array(); - //NewRelic Snippet - By JHL - //transactionLog($restConfig.PATH_DATA_SITE.SYS_TARGET); // ====> ??? this concat is very rare - - $RBAC->initRBAC(); - - Bootstrap::dispatchApiService(SYS_TARGET, API_VERSION); - } else { - //NewRelic Snippet - By JHL - transactionLog($phpFile); - require_once $phpFile; - } - - if (defined( 'SKIP_HEADERS' )) { - header( "Expires: " . gmdate( "D, d M Y H:i:s", mktime( 0, 0, 0, date( 'm' ), date( 'd' ), date( 'Y' ) + 1 ) ) . " GMT" ); - header( 'Cache-Control: public' ); - header( 'Pragma: ' ); - } - - ob_end_flush(); - if (DEBUG_TIME_LOG) { - bootstrap::logTimeByPage(); //log this page } } -} catch (Exception $e) { - //g::pr($e->getTrace()); die; - Bootstrap::renderTemplate('error.tpl', array( - 'title' => 'ProcessMaker Bootstrap Exception', - 'message' => nl2br($e->getMessage()), - 'exceptionClass' => get_class($e), - 'trace' => $e->getTrace() - )); +}*/ + +// load Plugins base class +Bootstrap::LoadClass( 'plugin' ); + +//here we are loading all plugins registered +//the singleton has a list of enabled plugins +$sSerializedFile = PATH_DATA_SITE . 'plugin.singleton'; +$oPluginRegistry = & PMPluginRegistry::getSingleton(); + +if (file_exists( $sSerializedFile )) { + $oPluginRegistry->unSerializeInstance( file_get_contents( $sSerializedFile ) ); + $attributes = $oPluginRegistry->getAttributes(); + Bootstrap::LoadTranslationPlugins( defined( 'SYS_LANG' ) ? SYS_LANG : "en" , $attributes); +} + +// setup propel definitions and logging +//changed to autoloader +//require_once ("propel/Propel.php"); +//require_once ("creole/Creole.php"); + +list($host, $port) = strpos(DB_HOST, ':') !== false ? explode(':', DB_HOST) : array(DB_HOST, ''); +$port = empty($port) ? '' : ";port=$port"; +$handler = new PmSessionHandler(DB_USER, DB_PASS, DB_ADAPTER.":host=$host;dbname=".DB_NAME.$port); + +session_start(); + +if (defined( 'DEBUG_SQL_LOG' ) && DEBUG_SQL_LOG) { + define( 'PM_PID', mt_rand( 1, 999999 ) ); + require_once 'Log.php'; + + // register debug connection decorator driver + Creole::registerDriver( '*', 'creole.contrib.DebugConnection' ); + + // initialize Propel with converted config file + Propel::init( PATH_CORE . "config/databases.php" ); + + // unified log file for all databases + $logFile = PATH_DATA . 'log' . PATH_SEP . 'propel.log'; + $logger = Log::singleton( 'file', $logFile, 'wf ' . SYS_SYS, null, PEAR_LOG_INFO ); + Propel::setLogger( $logger ); + // log file for workflow database + $con = Propel::getConnection( 'workflow' ); + if ($con instanceof DebugConnection) { + $con->setLogger( $logger ); + } + // log file for rbac database + $con = Propel::getConnection( 'rbac' ); + + if ($con instanceof DebugConnection) { + $con->setLogger( $logger ); + } + + // log file for report database + $con = Propel::getConnection( 'rp' ); + if ($con instanceof DebugConnection) { + $con->setLogger( $logger ); + } +} else { + Propel::init( PATH_CORE . "config/databases.php" ); +} + +Creole::registerDriver( 'dbarray', 'creole.contrib.DBArrayConnection' ); + +// Session Initializations +ini_set( 'session.auto_start', '1' ); + +// The register_globals feature has been DEPRECATED as of PHP 5.3.0. default value Off. +// ini_set( 'register_globals', 'Off' ); +//session_start(); +ob_start(); + +// Rebuild the base Workflow translations if not exists +if (! is_file( PATH_LANGUAGECONT . 'translation.en' )) { + require_once ("classes/model/Translation.php"); + $fields = Translation::generateFileTranslation( 'en' ); +} + +// TODO: Verify if the language set into url is defined in translations env. +if (SYS_LANG != 'en' && ! is_file( PATH_LANGUAGECONT . 'translation.' . SYS_LANG )) { + require_once ("classes/model/Translation.php"); + $fields = Translation::generateFileTranslation( SYS_LANG ); +} + +// Setup plugins +$oPluginRegistry->setupPlugins(); //get and setup enabled plugins +$avoidChangedWorkspaceValidation = false; + +// Load custom Classes and Model from Plugins. +Bootstrap::LoadAllPluginModelClasses(); + +// jump to php file in methods directory +$collectionPlugin = ''; +if ($oPluginRegistry->isRegisteredFolder( SYS_COLLECTION )) { + $phpFile = PATH_PLUGINS . SYS_COLLECTION . PATH_SEP . SYS_TARGET . '.php'; + $targetPlugin = explode( '/', SYS_TARGET ); + $collectionPlugin = $targetPlugin[0]; + $avoidChangedWorkspaceValidation = true; +} else { + $phpFile = Bootstrap::ExpandPath( 'methods' ) . SYS_COLLECTION . PATH_SEP . SYS_TARGET . '.php'; +} + +// services is a special folder, +if (SYS_COLLECTION == 'services') { + $avoidChangedWorkspaceValidation = true; + $targetPlugin = explode( '/', SYS_TARGET ); + + if ($targetPlugin[0] == 'webdav') { + $phpFile = Bootstrap::ExpandPath( 'methods' ) . SYS_COLLECTION . PATH_SEP . 'webdav.php'; + } +} + +if (SYS_COLLECTION == 'login' && SYS_TARGET == 'login') { + $avoidChangedWorkspaceValidation = true; +} + +$bWE = false; +$isControllerCall = false; +$isPluginController = false; + +if (substr( SYS_COLLECTION, 0, 8 ) === 'gulliver') { + $phpFile = PATH_GULLIVER_HOME . 'methods/' . substr( SYS_COLLECTION, 8 ) . SYS_TARGET . '.php'; +} else { + //when the file is part of the public directory of any PROCESS, this a ProcessMaker feature + if (preg_match( '/^[0-9][[:alnum:]]+$/', SYS_COLLECTION ) == 1) { //the pattern is /sysSYS/LANG/SKIN/PRO_UID/file + $auxPart = explode( '/', $_SERVER['REQUEST_URI'] ); + $aAux = explode( '?', $auxPart[count( $auxPart ) - 1] ); + //$extPart = explode ( '.' , $auxPart[ count($auxPart)-1] ); + $extPart = explode( '.', $aAux[0] ); + $queryPart = isset( $aAux[1] ) ? $aAux[1] : ""; + $extension = $extPart[count( $extPart ) - 1]; + $phpFile = PATH_DATA_SITE . 'public' . PATH_SEP . SYS_COLLECTION . PATH_SEP . urldecode( $auxPart[count( $auxPart ) - 1] ); + $aAux = explode( '?', $phpFile ); + $phpFile = $aAux[0]; + + if ($extension != 'php') { + //NewRelic Snippet - By JHL + transactionLog($phpFile); + Bootstrap::streamFile( $phpFile ); + die(); + } + + $avoidChangedWorkspaceValidation = true; + $bWE = true; + //$phpFile = PATH_DATA_SITE . 'public' . PATH_SEP . SYS_COLLECTION . PATH_SEP . $auxPart[ count($auxPart)-1]; + } + + //erik: verify if it is a Controller Class or httpProxyController Class + if (is_file( PATH_CONTROLLERS . SYS_COLLECTION . '.php' )) { + Bootstrap::LoadSystem( 'controller' ); + require_once PATH_CONTROLLERS . SYS_COLLECTION . '.php'; + $controllerClass = SYS_COLLECTION; + //if the method name is empty set default to index method + $controllerAction = SYS_TARGET != '' ? SYS_TARGET : 'index'; + //if the method exists + if (is_callable( Array ($controllerClass,$controllerAction ) )) { + $isControllerCall = true; + } + + if (substr(SYS_SKIN, 0, 2) != "ux" && $controllerClass == "main") { + $isControllerCall = false; + } + } + + if (is_dir(PATH_PLUGINS . SYS_COLLECTION) && $oPluginRegistry->isRegisteredFolder(SYS_COLLECTION)) { + $pluginName = SYS_COLLECTION; + $pluginResourceRequest = explode('/', rtrim(SYS_TARGET, '/')); + $isPluginController = true; + + if ($pluginResourceRequest > 0) { + $controllerClass = $pluginResourceRequest[0]; + + if (count($pluginResourceRequest) == 1) { + $controllerAction = 'index'; + } else { + $controllerAction = $pluginResourceRequest[1]; + } + } + + $pluginControllerPath = PATH_PLUGINS . $pluginName . PATH_SEP . 'controllers' . PATH_SEP; + + if (is_file($pluginControllerPath. $controllerClass . '.php')) { + require_once $pluginControllerPath. $controllerClass . '.php'; + } elseif (is_file($pluginControllerPath. ucfirst($controllerClass) . '.php')) { + $controllerClass = ucfirst($controllerClass); + require_once $pluginControllerPath. $controllerClass . '.php'; + } elseif (is_file($pluginControllerPath. ucfirst($controllerClass) . 'Controller.php')) { + $controllerClass = ucfirst($controllerClass) . 'Controller'; + require_once $pluginControllerPath. $controllerClass . '.php'; + } + + //if the method exists + if (is_callable(array($controllerClass, $controllerAction))) { + $isControllerCall = true; + } + } + + if (! $isControllerCall && ! file_exists( $phpFile ) && ! $isRestRequest) { + $_SESSION['phpFileNotFound'] = $_SERVER['REQUEST_URI']; + header( "location: /errors/error404.php?url=" . urlencode( $_SERVER['REQUEST_URI'] ) ); + die(); + } +} + +//redirect to login, if user changed the workspace in the URL +if (! $avoidChangedWorkspaceValidation && isset( $_SESSION['WORKSPACE'] ) && $_SESSION['WORKSPACE'] != SYS_SYS) { + $_SESSION['WORKSPACE'] = SYS_SYS; + Bootstrap::SendTemporalMessage( 'ID_USER_HAVENT_RIGHTS_SYSTEM', "error" ); + // verify if the current skin is a 'ux' variant + $urlPart = substr( SYS_SKIN, 0, 2 ) == 'ux' && SYS_SKIN != 'uxs' ? '/main/login' : '/login/login'; + + header( 'Location: /sys' . SYS_SYS . '/' . SYS_LANG . '/' . SYS_SKIN . $urlPart ); + die(); +} + +// enable rbac +Bootstrap::LoadSystem( 'rbac' ); +$RBAC = &RBAC::getSingleton( PATH_DATA, session_id() ); +$RBAC->sSystem = 'PROCESSMAKER'; + +// define and send Headers for all pages +if (! defined( 'EXECUTE_BY_CRON' )) { + header( "Expires: " . gmdate( "D, d M Y H:i:s", mktime( 0, 0, 0, date( 'm' ), date( 'd' ) - 1, date( 'Y' ) ) ) . " GMT" ); + header( "Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . " GMT" ); + header( "Cache-Control: no-store, no-cache, must-revalidate" ); + header( "Cache-Control: post-check=0, pre-check=0", false ); + header( "Pragma: no-cache" ); + + // get the language direction from ServerConf + define( 'SYS_LANG_DIRECTION', $oServerConf->getLanDirection() ); + + if ((isset( $_SESSION['USER_LOGGED'] )) && (! (isset( $_GET['sid'] )))) { + if (preg_match("/msie/i", $_SERVER ['HTTP_USER_AGENT']) != 1 || $config['ie_cookie_lifetime'] == 1) { + if (PHP_VERSION < 5.2) { + setcookie(session_name(), session_id(), time() + $timelife, '/', '; HttpOnly'); + } else { + setcookie(session_name(), session_id(), time() + $timelife, '/', null, false, true); + } + } + $RBAC->initRBAC(); + //using optimization with memcache, the user data will be in memcache 8 hours, or until session id goes invalid + $memKey = 'rbacSession' . session_id(); + if (($RBAC->aUserInfo = $memcache->get( $memKey )) === false) { + $RBAC->loadUserRolePermission( $RBAC->sSystem, $_SESSION['USER_LOGGED'] ); + $memcache->set( $memKey, $RBAC->aUserInfo, PMmemcached::EIGHT_HOURS ); + } + } else { + // this is the blank list to allow execute scripts with no login (without session started) + $noLoginFiles = $noLoginFolders = array (); + $noLoginFiles[] = 'login'; + $noLoginFiles[] = 'authentication'; + $noLoginFiles[] = 'login_Ajax'; + $noLoginFiles[] = 'dbInfo'; + $noLoginFiles[] = 'sysLoginVerify'; + $noLoginFiles[] = 'processes_Ajax'; + $noLoginFiles[] = 'updateTranslation'; + $noLoginFiles[] = 'autoinstallProcesses'; + $noLoginFiles[] = 'autoinstallPlugins'; + $noLoginFiles[] = 'heartbeatStatus'; + $noLoginFiles[] = 'showLogoFile'; + $noLoginFiles[] = 'forgotPassword'; + $noLoginFiles[] = 'retrivePassword'; + $noLoginFiles[] = 'defaultAjaxDynaform'; + $noLoginFiles[] = 'dynaforms_checkDependentFields'; + $noLoginFiles[] = 'fields_Ajax'; + $noLoginFiles[] = 'appFolderAjax'; + $noLoginFiles[] = 'steps_Ajax'; + $noLoginFiles[] = 'proxyCasesList'; + $noLoginFiles[] = 'casesStartPage_Ajax'; + $noLoginFiles[] = 'appProxy'; + $noLoginFiles[] = 'cases_Ajax'; + $noLoginFiles[] = 'casesList_Ajax'; + $noLoginFiles[] = 'proxyReassignCasesList'; + $noLoginFiles[] = 'ajaxListener'; + $noLoginFiles[] = 'cases_Step'; + $noLoginFiles[] = 'cases_ShowOutputDocument'; + $noLoginFiles[] = 'cases_ShowDocument'; + $noLoginFiles[] = 'cases_CatchExecute'; + $noLoginFiles[] = 'cases_SaveData'; + $noLoginFiles[] = 'cases_Derivate'; + $noLoginFiles[] = 'cases_NextStep'; + $noLoginFiles[] = 'genericAjax'; + $noLoginFiles[] = 'casesSaveDataView'; + + $noLoginFolders[] = 'services'; + $noLoginFolders[] = 'tracker'; + $noLoginFolders[] = 'installer'; + + // This sentence is used when you lost the Session + if (! in_array( SYS_TARGET, $noLoginFiles ) && ! in_array( SYS_COLLECTION, $noLoginFolders ) && $bWE != true && $collectionPlugin != 'services' && ! $isRestRequest) { + $bRedirect = true; + if (isset( $_GET['sid'] )) { + Bootstrap::LoadClass( 'sessions' ); + $oSessions = new Sessions(); + if ($aSession = $oSessions->verifySession( $_GET['sid'] )) { + require_once 'classes/model/Users.php'; + $oUser = new Users(); + $aUser = $oUser->load( $aSession['USR_UID'] ); + $_SESSION['USER_LOGGED'] = $aUser['USR_UID']; + $_SESSION['USR_USERNAME'] = $aUser['USR_USERNAME']; + $bRedirect = false; + if (preg_match("/msie/i", $_SERVER ['HTTP_USER_AGENT']) != 1 || $config['ie_cookie_lifetime'] == 1) { + if (PHP_VERSION < 5.2) { + setcookie(session_name(), session_id(), time() + $timelife, '/', '; HttpOnly'); + } else { + setcookie(session_name(), session_id(), time() + $timelife, '/', null, false, true); + } + } + $RBAC->initRBAC(); + $RBAC->loadUserRolePermission( $RBAC->sSystem, $_SESSION['USER_LOGGED'] ); + $memKey = 'rbacSession' . session_id(); + $memcache->set( $memKey, $RBAC->aUserInfo, PMmemcached::EIGHT_HOURS ); + } + } + + if ($bRedirect) { + if (substr( SYS_SKIN, 0, 2 ) == 'ux' && SYS_SKIN != 'uxs') { // verify if the current skin is a 'ux' variant + $loginUrl = 'main/login'; + } else if (strpos( $_SERVER['REQUEST_URI'], '/home' ) !== false) { //verify is it is using the uxs skin for simplified interface + $loginUrl = 'home/login'; + } else { + $loginUrl = 'login/login'; // just set up the classic login + } + + if (empty( $_POST )) { + header( 'location: ' . SYS_URI . $loginUrl . '?u=' . urlencode( $_SERVER['REQUEST_URI'] ) ); + + } else { + if ($isControllerCall) { + header( "HTTP/1.0 302 session lost in controller" ); + } else { + header( 'location: ' . SYS_URI . $loginUrl ); + } + } + die(); + } + } + } + $_SESSION['phpLastFileFound'] = $_SERVER['REQUEST_URI']; + + /** + * New feature for Gulliver framework to support Controllers & HttpProxyController classes handling + * + * @author setHttpRequestData($_REQUEST);//NewRelic Snippet - By JHL + transactionLog($controllerAction); + + if ($isPluginController) { + $controller->setPluginName($pluginName); + $controller->setPluginHomeDir(PATH_PLUGINS . $pluginName . PATH_SEP); + } + + $controller->call($controllerAction); + } else { + //NewRelic Snippet - By JHL + transactionLog($phpFile); + require_once $phpFile; + } + + if (defined( 'SKIP_HEADERS' )) { + header( "Expires: " . gmdate( "D, d M Y H:i:s", mktime( 0, 0, 0, date( 'm' ), date( 'd' ), date( 'Y' ) + 1 ) ) . " GMT" ); + header( 'Cache-Control: public' ); + header( 'Pragma: ' ); + } + + ob_end_flush(); + if (DEBUG_TIME_LOG) { + bootstrap::logTimeByPage(); //log this page + } }