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";
40 * ------------- Standard getAuth/get/post methods of framework.
45 function getAuth() // everyone allowed in!!!!!
47 $this->loadOwnerCompany();
55 if (isset($this->_hasInit)) {
58 $this->_hasInit = true;
60 $boot = HTML_FlexyFramework::get();
61 // echo'<PRE>';print_R($boot);exit;
62 $this->appName= $boot->appName;
63 $this->appNameShort= $boot->appNameShort;
64 $this->appModules= $boot->enable;
65 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
66 $this->appDisable = $boot->disable;
67 $this->version = $boot->version;
69 if (!empty($ff->Pman['local_autoauth']) &&
70 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
71 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
82 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
83 $bits = explode('/', $base);
85 if ($bits[0] == 'Link') {
86 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
87 header('Content-type: text/html; charset=utf-8');
90 if ($bits[0] == 'PasswordReset') {
91 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
92 header('Content-type: text/html; charset=utf-8');
97 if ($this->getAuthUser()) {
98 $this->addEvent("RELOAD");
103 $this->addEvent("BADURL", false, $base);
104 $this->jerr("invalid url");
107 if (isset($_GET['onloadTrack'])) {
108 $this->onloadTrack = (int)$_GET['onloadTrack'];
110 // getting this to work with xhtml is a nightmare
111 // = nbsp / <img> issues screw everyting up.
112 //var_dump($this->isDev);
113 // force regeneration on load for development enviroments..
114 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
116 //header('Content-type: application/xhtml+xml; charset=utf-8');
117 header('Content-type: text/html; charset=utf-8');
120 function post($base) {
121 return $this->get($base);
125 * ------------- Authentication and permission info about logged in user!!!
130 function loadOwnerCompany()
132 $this->company = DB_DataObject::Factory('Companies');
133 if ($this->company) { // non-core pman projects
136 $this->company->get('comptype', 'OWNER');
139 function staticGetAuthUser()
141 $ff = HTML_FlexyFramework::get();
142 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
144 $u = DB_DataObject::factory($tbl);
148 return $u->getAuthUser();
150 function getAuthUser()
152 if (!empty($this->authUser)) {
153 return $this->authUser;
155 $ff = HTML_FlexyFramework::get();
156 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
158 $u = DB_DataObject::factory( $tbl );
162 $this->authUser =$u->getAuthUser();
163 return $this->authUser ;
165 function hasPerm($name, $lvl) // do we have a permission
167 static $pcache = array();
168 $au = $this->getAuthUser();
169 return $au->hasPerm($name,$lvl);
175 // appModules/appDisable contain a comma limited list of
176 // both modules and components that can be enabled/disabled..
178 // the modules call just lists the modules
179 $enabled = array('Core' => true);
180 $am = !empty($this->appModules) ? explode(',', $this->appModules) : array();
182 if (strpos( $k ,'.') ) {
190 $disabled = !empty($this->appDisable) ? explode(',', $this->appDisable) : array();
191 foreach($disabled as $k) {
192 if ( strpos( $k ,'.') ) {
195 if (isset($enabled[$k])) {
199 return array_keys($enabled);
202 function hasModule($name)
205 if (!strpos( $name,'.') ) {
206 // use enable / disable..
207 return in_array($name, $this->modules());
210 $x = DB_DataObject::factory('Group_Rights');
211 $ar = $x->defaultPermData();
212 if (empty($ar[$name]) || empty($ar[$name][0])) {
222 * ---------------- Global Tools ---------------
228 * send a template to the user
229 * rcpts are read from the resulting template.
231 * @arg $templateFile - the file in mail/XXXXXX.txt
232 * @arg $args - variables available to the form as {t.*} over and above 'this'
237 function sendTemplate($templateFile, $args)
242 $content = clone($this);
244 foreach((array)$args as $k=>$v) {
247 $content->msgid = md5(time() . rand());
249 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
250 /* use the regex compiler, as it doesnt parse <tags */
251 require_once 'HTML/Template/Flexy.php';
252 $template = new HTML_Template_Flexy( array(
253 'compiler' => 'Regex',
254 'filters' => array('SimpleTags','Mail'),
258 // this should be done by having multiple template sources...!!!
260 $template->compile('mail/'. $templateFile.'.txt');
262 /* use variables from this object to ouput data. */
263 $mailtext = $template->bufferedOutputObject($content);
264 //echo "<PRE>";print_R($mailtext);
266 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
267 require_once 'Mail/mimeDecode.php';
268 require_once 'Mail.php';
270 $decoder = new Mail_mimeDecode($mailtext);
271 $parts = $decoder->getSendArray();
272 if (PEAR::isError($parts)) {
274 //echo "PROBLEM: {$parts->message}";
277 list($recipents,$headers,$body) = $parts;
278 ///$recipents = array($this->email);
279 $mailOptions = PEAR::getStaticProperty('Mail','options');
280 $mail = Mail::factory("SMTP",$mailOptions);
281 $headers['Date'] = date('r');
282 if (PEAR::isError($mail)) {
285 $oe = error_reporting(E_ALL ^ E_NOTICE);
286 $ret = $mail->send($recipents,$headers,$body);
287 error_reporting($oe);
293 function checkFileUploadError() // check for file upload errors.
296 empty($_FILES['File'])
297 || empty($_FILES['File']['name'])
298 || empty($_FILES['File']['tmp_name'])
299 || empty($_FILES['File']['type'])
300 || !empty($_FILES['File']['error'])
301 || empty($_FILES['File']['size'])
303 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
309 * generate a tempory file with an extension (dont forget to delete it)
312 function tempName($ext)
314 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
316 return $x .'.'. $ext;
319 * ------------- Authentication testing ------ ??? MOVEME?
323 function linkAuth($trid, $trkey)
325 $tr = DB_DataObject::factory('Documents_Tracking');
326 if (!$tr->get($trid)) {
327 return "Invalid URL";
329 if (strtolower($tr->authkey) != strtolower($trkey)) {
330 $this->AddEvent("ERROR-L", false, "Invalid Key");
331 return "Invalid KEY";
334 $this->onloadTrack = (int) $tr->doc_id;
335 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
336 $this->AddEvent("ERROR-L", false, "Key Expired");
337 return "Key Expired";
339 // user logged in and not
340 $au = $this->getAuthUser();
341 if ($au && $au->id && $au->id != $tr->person_id) {
344 return "Logged Out existing Session\n - reload to log in with correct key";
346 if ($au) { // logged in anyway..
347 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
348 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
353 // authenticate the user...
355 $u = DB_DataObject::factory('Person');
357 $u->get($tr->person_id);
359 $this->AddEvent("LOGIN", false, "With Key");
361 // we need to redirect out - otherwise refererer url will include key!
362 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
374 * ------------- Authentication password reset ------ ??? MOVEME?
380 function resetPassword($id,$t, $key)
383 $au = $this->getAuthUser();
385 return "Already Logged in - no need to use Password Reset";
388 $u = DB_DataObject::factory('Person');
389 //$u->company_id = $this->company->id;
391 if (!$u->get($id) || !strlen($u->passwd)) {
396 if ($key != $u->genPassKey($t)) {
397 return "invalid key";
400 $u->no_reset_sent = 0;
403 if ($t < strtotime("NOW - 1 DAY")) {
406 $this->showNewPass = implode("/", array($id,$t,$key));
412 * ---------------- Standard JSON outputers. - used everywhere
415 function jerr($str, $errors=array()) // standard error reporting..
417 require_once 'Services/JSON.php';
418 $json = new Services_JSON();
421 $this->addEvent("ERROR", false, $str);
423 if (!empty($_REQUEST['returnHTML']) ||
424 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
426 header('Content-type: text/html');
427 echo "<HTML><HEAD></HEAD><BODY>";
428 echo $json->encodeUnsafe(array(
431 'message' => $str, // compate with exeption / loadexception.
433 'errors' => $errors ? $errors : true, // used by forms to flag errors.
434 'authFailure' => !empty($errors['authFailure']),
436 echo "</BODY></HTML>";
440 echo $json->encode(array(
444 'message' => $str, // compate with exeption / loadexception.
445 'errors' => $errors ? $errors : true, // used by forms to flag errors.
446 'authFailure' => !empty($errors['authFailure']),
454 require_once 'Services/JSON.php';
455 $json = new Services_JSON();
457 if (!empty($_REQUEST['returnHTML']) ||
458 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
461 header('Content-type: text/html');
462 echo "<HTML><HEAD></HEAD><BODY>";
463 echo $json->encodeUnsafe(array('success'=> true, 'data' => $str));
464 echo "</BODY></HTML>";
469 echo $json->encode(array('success'=> true, 'data' => $str));
474 * output data for grids or tree
475 * @ar {Array} ar Array of data
476 * @total {Number|false} total number of records (or false to return count(ar)
477 * @extra {Array} extra key value list of data to pass as extra data.
480 function jdata($ar,$total=false, $extra=array())
482 // should do mobile checking???
483 if ($total == false) {
486 $extra= $extra ? $extra : array();
487 require_once 'Services/JSON.php';
488 $json = new Services_JSON();
489 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
500 * ---------------- Page output?!?!?
504 function hasBg($fn) // used on front page to check if logos exist..
506 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
509 function outputJavascriptIncludes() // includes on devel version..
512 $mods = explode(',', $this->appModules);
513 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
514 array_unshift($mods, 'Core');
517 $mods = array_unique($mods);
519 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
521 foreach($mods as $mod) {
522 // add the css file..
523 if (in_array($mod, $disabled)) {
528 $files = $this->moduleJavascriptList($mod.'/widgets');
529 foreach($files as $f) {
530 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
533 $files = $this->moduleJavascriptList($mod);
534 foreach($files as $f) {
535 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
542 function outputCSSIncludes() // includes on CSS links.
545 $mods = explode(',', $this->appModules);
546 array_unshift($mods, 'Core');
547 $mods = array_unique($mods);
549 foreach($mods as $mod) {
550 // add the css file..
551 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
552 if (file_exists( $css)){
553 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
554 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
565 function moduleJavascriptList($mod)
568 $ff = HTML_FlexyFramework::get();
570 $dir = $this->rootDir.'/Pman/'. $mod;
572 $path = $this->rootURL."/Pman/$mod/";
573 $base = dirname($_SERVER['SCRIPT_FILENAME']);
574 $cfile = realpath($base .'/_compiled_/' . $mod);
575 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
577 if (!file_exists($dir)) {
585 if (file_exists($cfile)) {
586 // $ctime = max(filemtime($cfile), filectime($cfile));
587 // otherwise use compile dfile..
589 $ar = glob($cfile . '/' . $mod . '*.js');
590 // default to first..
591 $cfile = basename($ar[count($ar) -1]);
592 foreach($ar as $fn) {
593 if (filemtime($fn) > $maxm) {
594 $cfile = basename($fn);
595 $maxm = filemtime($fn);
601 $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
602 if (file_exists($lfile)) {
603 array_push($files, $this->rootURL."/_translations_/$mod.js");
607 // works out if stuff has been updated..
608 // technically the non-dev version should output compiled only?!!?
610 while (false !== ($f = readdir($dh))) {
612 if (!preg_match('/\.js$/', $f)) {
615 // got the 'module file..'
617 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
618 $files[] = $path . $f;
623 // var_dump(array($maxtime , $ctime));
624 //if ($maxtime > $ctime) {
625 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
626 usort($files, $lsort);
627 // if (file_exists($lfile)) {
628 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
639 * ---------------- Logging ---------------
644 * Log an action (only if it has not been logged already.
646 * @param {String} action - group/name of event
647 * @param {DataObject|false} obj - dataobject action occured on.
648 * @param {String} any remarks
651 function addEventOnce($act, $obj = false, $remarks = '')
653 $au = $this->getAuthUser();
654 $e = DB_DataObject::factory('Events');
655 $e->init($act,$obj,$remarks);
656 if ($e->find(true)) {
659 $this->addEvent($act, $obj, $remarks);
665 * @param {String} action - group/name of event
666 * @param {DataObject|false} obj - dataobject action occured on.
667 * @param {String} any remarks
670 function addEvent($act, $obj = false, $remarks = '')
672 $au = $this->getAuthUser();
673 $e = DB_DataObject::factory('Events');
674 $e->init($act,$obj,$remarks);
676 $e->event_when = date('Y-m-d H:i:s');
679 $ff = HTML_FlexyFramework::get();
680 if (empty($ff->Pman['event_log_dir'])) {
683 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
684 if (!file_exists(dirname($file))) {
685 mkdir(dirname($file),0700,true);
687 file_put_contents($file, var_export(array(
688 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
689 'GET' => empty($_GET) ? array() : $_GET,
690 'POST' => empty($_POST) ? array() : $_POST,