6 * - base application setup (variables etc to javascript)
8 * - authentication and permission info about user / application
9 * - json output methods.
10 * - file upload error checking - checkFileUploadError
11 * - logging to event table
12 * - sendTemplate code (normally use the Person version for sending to specific people..)
14 * - doc managment code?? - remarks and tracking??? - MOVEME
15 * - authentication link checking?? MOVEME?
16 * - authentication reset password ?? MOVEME?
17 * ?? arrayClean.. what's it doing here?!? ;)
20 * DB_DataObject*:*toEventString (for logging - this is generically prefixed to all database operations.)
21 * - any data object where this method exists, the result will get prefixed to the log remarks
24 class Pman extends HTML_FlexyFramework_Page
27 var $appShortName= "";
28 var $appVersion = "1.8";
35 var $appDisabled = array(); // array of disabled modules..
36 // (based on config option disable)
38 var $authUser; // always contains the authenticated user..
43 * ------------- Standard getAuth/get/post methods of framework.
48 function getAuth() // everyone allowed in!!!!!
50 $this->loadOwnerCompany();
58 if (isset($this->_hasInit)) {
61 $this->_hasInit = true;
63 $boot = HTML_FlexyFramework::get();
64 // echo'<PRE>';print_R($boot);exit;
65 $this->appName= $boot->appName;
66 $this->appNameShort= $boot->appNameShort;
67 $this->appModules= $boot->enable;
68 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
69 $this->appDisable = $boot->disable;
70 $this->appDisabled = explode(',', $boot->disable);
71 $this->version = $boot->version;
73 if (!empty($ff->Pman['local_autoauth']) &&
74 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
75 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
85 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
86 $bits = explode('/', $base);
88 if ($bits[0] == 'Link') {
89 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
90 header('Content-type: text/html; charset=utf-8');
93 if ($bits[0] == 'PasswordReset') {
94 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
95 header('Content-type: text/html; charset=utf-8');
100 if ($this->getAuthUser()) {
101 $this->addEvent("RELOAD");
106 $this->addEvent("BADURL", false, $base);
107 $this->jerr("invalid url");
110 if (isset($_GET['onloadTrack'])) {
111 $this->onloadTrack = (int)$_GET['onloadTrack'];
113 // getting this to work with xhtml is a nightmare
114 // = nbsp / <img> issues screw everyting up.
115 //var_dump($this->isDev);
116 // force regeneration on load for development enviroments..
118 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
120 //header('Content-type: application/xhtml+xml; charset=utf-8');
121 header('Content-type: text/html; charset=utf-8');
124 function post($base) {
125 return $this->get($base);
129 * ------------- Authentication and permission info about logged in user!!!
134 function loadOwnerCompany()
136 $this->company = DB_DataObject::Factory('Companies');
137 if ($this->company) { // non-core pman projects
140 $this->company->get('comptype', 'OWNER');
143 function staticGetAuthUser()
145 $ff = HTML_FlexyFramework::get();
146 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
148 $u = DB_DataObject::factory($tbl);
152 return $u->getAuthUser();
154 function getAuthUser()
156 if (!empty($this->authUser)) {
157 return $this->authUser;
159 $ff = HTML_FlexyFramework::get();
160 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
162 $u = DB_DataObject::factory( $tbl );
166 $this->authUser =$u->getAuthUser();
167 return $this->authUser ;
169 function hasPerm($name, $lvl) // do we have a permission
171 static $pcache = array();
172 $au = $this->getAuthUser();
173 return $au->hasPerm($name,$lvl);
179 // appModules/appDisable contain a comma limited list of
180 // both modules and components that can be enabled/disabled..
181 $boot = HTML_FlexyFramework::get();
183 // the modules call just lists the modules
184 $enabled = array('Core' => true);
185 $am = !empty($boot->enable) ? explode(',', $boot->enable) : array();
187 if (strpos( $k ,'.') ) {
194 $disabled = !empty($boot->disable) ? explode(',', $boot->disable) : array();
195 foreach($disabled as $k) {
196 if ( strpos( $k ,'.') ) {
199 if (isset($enabled[$k])) {
203 //echo '<PRE>'; var_Dump($enabled);
205 return array_keys($enabled);
208 function hasModule($name)
211 if (!strpos( $name,'.') ) {
212 // use enable / disable..
213 return in_array($name, $this->modules());
216 $x = DB_DataObject::factory('Group_Rights');
217 $ar = $x->defaultPermData();
218 if (empty($ar[$name]) || empty($ar[$name][0])) {
228 * ---------------- Global Tools ---------------
234 * send a template to the user
235 * rcpts are read from the resulting template.
237 * @arg $templateFile - the file in mail/XXXXXX.txt
238 * @arg $args - variables available to the form as {t.*} over and above 'this'
243 function sendTemplate($templateFile, $args)
248 $content = clone($this);
250 foreach((array)$args as $k=>$v) {
253 $content->msgid = md5(time() . rand());
255 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
256 /* use the regex compiler, as it doesnt parse <tags */
257 require_once 'HTML/Template/Flexy.php';
258 $template = new HTML_Template_Flexy( array(
259 'compiler' => 'Regex',
260 'filters' => array('SimpleTags','Mail'),
264 // this should be done by having multiple template sources...!!!
266 $template->compile('mail/'. $templateFile.'.txt');
268 /* use variables from this object to ouput data. */
269 $mailtext = $template->bufferedOutputObject($content);
270 //echo "<PRE>";print_R($mailtext);
272 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
273 require_once 'Mail/mimeDecode.php';
274 require_once 'Mail.php';
276 $decoder = new Mail_mimeDecode($mailtext);
277 $parts = $decoder->getSendArray();
278 if (PEAR::isError($parts)) {
280 //echo "PROBLEM: {$parts->message}";
283 list($recipents,$headers,$body) = $parts;
284 ///$recipents = array($this->email);
285 $mailOptions = PEAR::getStaticProperty('Mail','options');
286 $mail = Mail::factory("SMTP",$mailOptions);
287 $headers['Date'] = date('r');
288 if (PEAR::isError($mail)) {
291 $oe = error_reporting(E_ALL ^ E_NOTICE);
292 $ret = $mail->send($recipents,$headers,$body);
293 error_reporting($oe);
299 function checkFileUploadError() // check for file upload errors.
302 empty($_FILES['File'])
303 || empty($_FILES['File']['name'])
304 || empty($_FILES['File']['tmp_name'])
305 || empty($_FILES['File']['type'])
306 || !empty($_FILES['File']['error'])
307 || empty($_FILES['File']['size'])
309 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
315 * generate a tempory file with an extension (dont forget to delete it)
318 function tempName($ext)
320 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
322 return $x .'.'. $ext;
325 * ------------- Authentication testing ------ ??? MOVEME?
329 function linkAuth($trid, $trkey)
331 $tr = DB_DataObject::factory('Documents_Tracking');
332 if (!$tr->get($trid)) {
333 return "Invalid URL";
335 if (strtolower($tr->authkey) != strtolower($trkey)) {
336 $this->AddEvent("ERROR-L", false, "Invalid Key");
337 return "Invalid KEY";
340 $this->onloadTrack = (int) $tr->doc_id;
341 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
342 $this->AddEvent("ERROR-L", false, "Key Expired");
343 return "Key Expired";
345 // user logged in and not
346 $au = $this->getAuthUser();
347 if ($au && $au->id && $au->id != $tr->person_id) {
350 return "Logged Out existing Session\n - reload to log in with correct key";
352 if ($au) { // logged in anyway..
353 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
354 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
359 // authenticate the user...
361 $u = DB_DataObject::factory('Person');
363 $u->get($tr->person_id);
365 $this->AddEvent("LOGIN", false, "With Key");
367 // we need to redirect out - otherwise refererer url will include key!
368 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
380 * ------------- Authentication password reset ------ ??? MOVEME?
386 function resetPassword($id,$t, $key)
389 $au = $this->getAuthUser();
391 return "Already Logged in - no need to use Password Reset";
394 $u = DB_DataObject::factory('Person');
395 //$u->company_id = $this->company->id;
397 if (!$u->get($id) || !strlen($u->passwd)) {
402 if ($key != $u->genPassKey($t)) {
403 return "invalid key";
406 $u->no_reset_sent = 0;
409 if ($t < strtotime("NOW - 1 DAY")) {
412 $this->showNewPass = implode("/", array($id,$t,$key));
417 * jerrAuth: standard auth failure - with data that let's the UI know..
421 $this->jerr("Not authenticated", array('authFailure' => true));
425 * ---------------- Standard JSON outputers. - used everywhere
428 function jerr($str, $errors=array()) // standard error reporting..
431 $cli = HTML_FlexyFramework::get()->cli;
433 echo "ERROR:\n" .$str . "\n";
437 require_once 'Services/JSON.php';
438 $json = new Services_JSON();
441 $this->addEvent("ERROR", false, $str);
443 if (!empty($_REQUEST['returnHTML']) ||
444 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
446 header('Content-type: text/html');
447 echo "<HTML><HEAD></HEAD><BODY>";
448 echo $json->encodeUnsafe(array(
451 'message' => $str, // compate with exeption / loadexception.
453 'errors' => $errors ? $errors : true, // used by forms to flag errors.
454 'authFailure' => !empty($errors['authFailure']),
456 echo "</BODY></HTML>";
460 echo $json->encode(array(
464 'message' => $str, // compate with exeption / loadexception.
465 'errors' => $errors ? $errors : true, // used by forms to flag errors.
466 'authFailure' => !empty($errors['authFailure']),
474 require_once 'Services/JSON.php';
475 $json = new Services_JSON();
477 if (!empty($_REQUEST['returnHTML']) ||
478 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
481 header('Content-type: text/html');
482 echo "<HTML><HEAD></HEAD><BODY>";
483 // encode html characters so they can be read..
484 echo str_replace(array('<','>'), array('\u003c','\u003e'),
485 $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
486 echo "</BODY></HTML>";
491 echo $json->encode(array('success'=> true, 'data' => $str));
496 * output data for grids or tree
497 * @ar {Array} ar Array of data
498 * @total {Number|false} total number of records (or false to return count(ar)
499 * @extra {Array} extra key value list of data to pass as extra data.
502 function jdata($ar,$total=false, $extra=array())
504 // should do mobile checking???
505 if ($total == false) {
508 $extra= $extra ? $extra : array();
509 require_once 'Services/JSON.php';
510 $json = new Services_JSON();
511 if (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE'])) {
513 header('Content-type: text/html');
514 echo "<HTML><HEAD></HEAD><BODY>";
515 // encode html characters so they can be read..
516 echo str_replace(array('<','>'), array('\u003c','\u003e'),
517 $json->encodeUnsafe(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra));
518 echo "</BODY></HTML>";
528 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
539 * ---------------- Page output?!?!?
543 function hasBg($fn) // used on front page to check if logos exist..
545 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
548 function outputJavascriptIncludes() // includes on devel version..
551 $mods = explode(',', $this->appModules);
552 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
553 array_unshift($mods, 'Core');
556 $mods = array_unique($mods);
558 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
560 foreach($mods as $mod) {
561 // add the css file..
562 if (in_array($mod, $disabled)) {
567 $files = $this->moduleJavascriptList($mod.'/widgets');
568 foreach($files as $f) {
569 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
572 $files = $this->moduleJavascriptList($mod);
573 foreach($files as $f) {
574 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
581 function outputCSSIncludes() // includes on CSS links.
584 $mods = explode(',', $this->appModules);
585 array_unshift($mods, 'Core');
586 $mods = array_unique($mods);
588 foreach($mods as $mod) {
589 // add the css file..
590 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
591 if (file_exists( $css)){
592 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
593 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
608 function packJS($dir)
611 // target has to be 'aliased'
612 // target filename can be an md5..
614 require_once 'Pman/Core/JsCompile.php';
615 $x = new Pman_Core_JsCompile();
616 $x->packScript(dirname(__FILE__).'/Hex/templates/images',
618 $this->rootURL . '/Hex/templates/images');
623 * Gather infor for javascript files..
625 * @param {String} $mod the module to get info about.
626 * @return {StdClass} details about module.
628 function moduleJavascriptFilesInfo($mod)
630 $ff = HTML_FlexyFramework::get();
632 $base = dirname($_SERVER['SCRIPT_FILENAME']);
633 $dir = $this->rootDir.'/Pman/'. $mod;
636 $ar = glob($dir . '/*.js');
642 foreach($ar as $fn) {
644 // got the 'module file..'
645 $mtime = filemtime($dir . '/'. $f);
646 $maxtime = max($mtime, $maxtime);
647 $arfiles[$fn] = $mtime;
648 $files[] = $path . $f . '?ts='.$mtime;
650 $compile = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
651 $basedir = $ff->Pman['public_cache_dir'];
652 $baseurl = $ff->Pman['public_cache_url'];
654 return (object) array(
656 'filesmtime' => $arfiles,
657 'maxtime' => $maxtime,
658 'compile' => $compile,
659 'translation_file' => realpath($base .'/_translations_/' . str_replace('/','.', $mod) . '.js'),
660 'output' => date('Y-m-d-H-i-s-', $maxtime). str_replace('/','.',$mod).'-'.md5(serialize($arfiles)) .'.js',
661 'basedir' => $basedir,
662 'baseurl' => $baseurl,
670 * moduleJavascriptList: list the javascript files in a module
672 * The original version of this.. still needs more thought...
674 * Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
675 * Translations are in Pman/_translations_/{$mod}.js
677 * if that stuff does not exist just list files in Pman/{$mod}/*.js
679 * Compiled could be done on the fly..
683 * @param {String} $mod the module to look at - eg. Pman/{$mod}/*.js
684 * @return {Array} list of include paths (either compiled or raw)
690 function moduleJavascriptList($mod)
694 $dir = $this->rootDir.'/Pman/'. $mod;
695 if (!file_exists($dir)) {
699 $info = $this->moduleJavascriptFilesInfo($mod);
704 if (empty($info->files)) {
707 // finally sort the files, so they are in the right order..
709 // only compile this stuff if public_cache is set..
711 $compile = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
714 // public_cache_dir = /var/www/myproject_cache
715 // public_cache_url = /myproject_cache (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
717 $basedir = empty($ff->Pman['public_cache_dir']) ? false : $ff->Pman['public_cache_dir'];
718 $baseurl = empty($ff->Pman['public_cache_url']) ? false : $ff->Pman['public_cache_url'];
721 $output = date('Y-m-d-H-i-s-', $maxtime). str_replace('/','.',$mod).'-'.md5(serialize($arfiles)) .'.js';
723 // where are we going to write all of this..
724 // This has to be done via a
725 if ( $compile && !file_exists($basedir.'/'.$output)) {
726 require_once 'Pman/Core/JsCompile.php';
727 $x = new Pman_Core_JsCompile();
729 $x->pack($arfiles,$basedir.'/'.$output );
732 if ($compile && file_exists($basedir.'/'.$output) && filesize($basedir.'/'.$output)) {
735 $baseurl.'/'. $output,
736 $this->rootURL."/_translations_/". str_replace('/','.', $mod).".js"
742 // give up and output original files...
743 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
744 usort($files, $lsort);
754 * ---------------- Logging ---------------
759 * Log an action (only if it has not been logged already.
761 * @param {String} action - group/name of event
762 * @param {DataObject|false} obj - dataobject action occured on.
763 * @param {String} any remarks
766 function addEventOnce($act, $obj = false, $remarks = '')
768 $au = $this->getAuthUser();
769 $e = DB_DataObject::factory('Events');
770 $e->init($act,$obj,$remarks);
771 if ($e->find(true)) {
774 return $this->addEvent($act, $obj, $remarks);
780 * @param {String} action - group/name of event
781 * @param {DataObject|false} obj - dataobject action occured on.
782 * @param {String} any remarks
783 * @return {Number} Event id.,
786 function addEvent($act, $obj = false, $remarks = '')
788 $au = $this->getAuthUser();
789 $e = DB_DataObject::factory('Events');
790 $e->init($act,$obj,$remarks);
792 $e->event_when = date('Y-m-d H:i:s');
795 $ff = HTML_FlexyFramework::get();
796 if (empty($ff->Pman['event_log_dir'])) {
799 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
800 if (!file_exists(dirname($file))) {
801 mkdir(dirname($file),0700,true);
803 file_put_contents($file, var_export(array(
804 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
805 'GET' => empty($_GET) ? array() : $_GET,
806 'POST' => empty($_POST) ? array() : $_POST,