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');
625 * moduleJavascriptList: list the javascript files in a module
627 * The original version of this.. still needs more thought...
629 * Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
630 * Translations are in Pman/_translations_/{$mod}.js
632 * if that stuff does not exist just list files in Pman/{$mod}/*.js
634 * Compiled could be done on the fly..
638 * @param {String} $mod the module to look at - eg. Pman/{$mod}/*.js
639 * @return {Array} list of include paths (either compiled or raw)
645 function moduleJavascriptList($mod)
648 $ff = HTML_FlexyFramework::get();
650 $dir = $this->rootDir.'/Pman/'. $mod;
652 $path = $this->rootURL."/Pman/$mod/";
653 $base = dirname($_SERVER['SCRIPT_FILENAME']);
654 $cfile = realpath($base .'/_compiled_/' . $mod);
655 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
657 if (!file_exists($dir)) {
665 // compiled directory exists...
666 if (file_exists($cfile)) {
667 // $ctime = max(filemtime($cfile), filectime($cfile));
668 // otherwise use compile dfile..
670 $ar = glob($cfile . '/' . $mod . '*.js');
671 // default to first..
672 $cfile = basename($ar[count($ar) -1]);
673 foreach($ar as $fn) {
674 if (filemtime($fn) > $maxm) {
675 $cfile = basename($fn);
676 $maxm = filemtime($fn);
681 $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
682 if (file_exists($lfile)) {
683 array_push($files, $this->rootURL."/_translations_/$mod.js");
687 // works out if stuff has been updated..
688 // technically the non-dev version should output compiled only?!!?
689 $ar = glob($dir . '/*.js');
691 foreach($ar as $fn) {
693 // got the 'module file..'
694 $mtime = filemtime($dir . '/'. $f);
695 $maxtime = max($mtime, $maxtime);
696 $arfiles[$mtime] = $fn;
697 $files[] = $path . $f . '?ts='.$mtime;
703 // finally sort the files, so they are in the right order..
705 // only compile this stuff if public_cache is set..
707 $compile = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
710 // public_cache_dir = /var/www/myproject_cache
711 // public_cache_url = /myproject_cache (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
713 $basedir = $ff->Pman['public_cache_dir'];
714 $baseurl = $ff->Pman['public_cache_url'];
717 $output = date('Y-m-d-H-i-s-').$mod.'-'.md5(serialize($arfiles)) .'.js';
719 // where are we going to write all of this..
720 // This has to be done via a
721 if ( $compile && !file_exists($basedir.'/'.$output)) {
722 $this->pack($arfiles,$basedir.'/'.$output);
725 if ($compile && file_exists($basedir.'/_cache_/'.$output)) {
728 $baseurl.'/'. $output,
729 $this->rootURL."/_translations_/$mod.js"
735 // give up and output original files...
736 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
737 usort($files, $lsort);
747 * ---------------- Logging ---------------
752 * Log an action (only if it has not been logged already.
754 * @param {String} action - group/name of event
755 * @param {DataObject|false} obj - dataobject action occured on.
756 * @param {String} any remarks
759 function addEventOnce($act, $obj = false, $remarks = '')
761 $au = $this->getAuthUser();
762 $e = DB_DataObject::factory('Events');
763 $e->init($act,$obj,$remarks);
764 if ($e->find(true)) {
767 return $this->addEvent($act, $obj, $remarks);
773 * @param {String} action - group/name of event
774 * @param {DataObject|false} obj - dataobject action occured on.
775 * @param {String} any remarks
776 * @return {Number} Event id.,
779 function addEvent($act, $obj = false, $remarks = '')
781 $au = $this->getAuthUser();
782 $e = DB_DataObject::factory('Events');
783 $e->init($act,$obj,$remarks);
785 $e->event_when = date('Y-m-d H:i:s');
788 $ff = HTML_FlexyFramework::get();
789 if (empty($ff->Pman['event_log_dir'])) {
792 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
793 if (!file_exists(dirname($file))) {
794 mkdir(dirname($file),0700,true);
796 file_put_contents($file, var_export(array(
797 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
798 'GET' => empty($_GET) ? array() : $_GET,
799 'POST' => empty($_POST) ? array() : $_POST,