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";
37 var $authUser; // always contains the authenticated user..
42 * ------------- Standard getAuth/get/post methods of framework.
47 function getAuth() // everyone allowed in!!!!!
49 $this->loadOwnerCompany();
57 if (isset($this->_hasInit)) {
60 $this->_hasInit = true;
62 $boot = HTML_FlexyFramework::get();
63 // echo'<PRE>';print_R($boot);exit;
64 $this->appName= $boot->appName;
65 $this->appNameShort= $boot->appNameShort;
66 $this->appModules= $boot->enable;
67 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
68 $this->appDisable = $boot->disable;
69 $this->version = $boot->version;
71 if (!empty($ff->Pman['local_autoauth']) &&
72 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
73 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
84 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
85 $bits = explode('/', $base);
87 if ($bits[0] == 'Link') {
88 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
89 header('Content-type: text/html; charset=utf-8');
92 if ($bits[0] == 'PasswordReset') {
93 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
94 header('Content-type: text/html; charset=utf-8');
99 if ($this->getAuthUser()) {
100 $this->addEvent("RELOAD");
105 $this->addEvent("BADURL", false, $base);
106 $this->jerr("invalid url");
109 if (isset($_GET['onloadTrack'])) {
110 $this->onloadTrack = (int)$_GET['onloadTrack'];
112 // getting this to work with xhtml is a nightmare
113 // = nbsp / <img> issues screw everyting up.
114 //var_dump($this->isDev);
115 // force regeneration on load for development enviroments..
116 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
118 //header('Content-type: application/xhtml+xml; charset=utf-8');
119 header('Content-type: text/html; charset=utf-8');
122 function post($base) {
123 return $this->get($base);
127 * ------------- Authentication and permission info about logged in user!!!
132 function loadOwnerCompany()
134 $this->company = DB_DataObject::Factory('Companies');
135 if ($this->company) { // non-core pman projects
138 $this->company->get('comptype', 'OWNER');
141 function staticGetAuthUser()
143 $ff = HTML_FlexyFramework::get();
144 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
146 $u = DB_DataObject::factory($tbl);
150 return $u->getAuthUser();
152 function getAuthUser()
154 if (!empty($this->authUser)) {
155 return $this->authUser;
157 $ff = HTML_FlexyFramework::get();
158 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
160 $u = DB_DataObject::factory( $tbl );
164 $this->authUser =$u->getAuthUser();
165 return $this->authUser ;
167 function hasPerm($name, $lvl) // do we have a permission
169 static $pcache = array();
170 $au = $this->getAuthUser();
171 return $au->hasPerm($name,$lvl);
177 // appModules/appDisable contain a comma limited list of
178 // both modules and components that can be enabled/disabled..
179 $boot = HTML_FlexyFramework::get();
181 // the modules call just lists the modules
182 $enabled = array('Core' => true);
183 $am = !empty($boot->enable) ? explode(',', $boot->enable) : array();
185 if (strpos( $k ,'.') ) {
192 $disabled = !empty($boot->disable) ? explode(',', $boot->disable) : array();
193 foreach($disabled as $k) {
194 if ( strpos( $k ,'.') ) {
197 if (isset($enabled[$k])) {
201 //echo '<PRE>'; var_Dump($enabled);
203 return array_keys($enabled);
206 function hasModule($name)
209 if (!strpos( $name,'.') ) {
210 // use enable / disable..
211 return in_array($name, $this->modules());
214 $x = DB_DataObject::factory('Group_Rights');
215 $ar = $x->defaultPermData();
216 if (empty($ar[$name]) || empty($ar[$name][0])) {
226 * ---------------- Global Tools ---------------
232 * send a template to the user
233 * rcpts are read from the resulting template.
235 * @arg $templateFile - the file in mail/XXXXXX.txt
236 * @arg $args - variables available to the form as {t.*} over and above 'this'
241 function sendTemplate($templateFile, $args)
246 $content = clone($this);
248 foreach((array)$args as $k=>$v) {
251 $content->msgid = md5(time() . rand());
253 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
254 /* use the regex compiler, as it doesnt parse <tags */
255 require_once 'HTML/Template/Flexy.php';
256 $template = new HTML_Template_Flexy( array(
257 'compiler' => 'Regex',
258 'filters' => array('SimpleTags','Mail'),
262 // this should be done by having multiple template sources...!!!
264 $template->compile('mail/'. $templateFile.'.txt');
266 /* use variables from this object to ouput data. */
267 $mailtext = $template->bufferedOutputObject($content);
268 //echo "<PRE>";print_R($mailtext);
270 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
271 require_once 'Mail/mimeDecode.php';
272 require_once 'Mail.php';
274 $decoder = new Mail_mimeDecode($mailtext);
275 $parts = $decoder->getSendArray();
276 if (PEAR::isError($parts)) {
278 //echo "PROBLEM: {$parts->message}";
281 list($recipents,$headers,$body) = $parts;
282 ///$recipents = array($this->email);
283 $mailOptions = PEAR::getStaticProperty('Mail','options');
284 $mail = Mail::factory("SMTP",$mailOptions);
285 $headers['Date'] = date('r');
286 if (PEAR::isError($mail)) {
289 $oe = error_reporting(E_ALL ^ E_NOTICE);
290 $ret = $mail->send($recipents,$headers,$body);
291 error_reporting($oe);
297 function checkFileUploadError() // check for file upload errors.
300 empty($_FILES['File'])
301 || empty($_FILES['File']['name'])
302 || empty($_FILES['File']['tmp_name'])
303 || empty($_FILES['File']['type'])
304 || !empty($_FILES['File']['error'])
305 || empty($_FILES['File']['size'])
307 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
313 * generate a tempory file with an extension (dont forget to delete it)
316 function tempName($ext)
318 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
320 return $x .'.'. $ext;
323 * ------------- Authentication testing ------ ??? MOVEME?
327 function linkAuth($trid, $trkey)
329 $tr = DB_DataObject::factory('Documents_Tracking');
330 if (!$tr->get($trid)) {
331 return "Invalid URL";
333 if (strtolower($tr->authkey) != strtolower($trkey)) {
334 $this->AddEvent("ERROR-L", false, "Invalid Key");
335 return "Invalid KEY";
338 $this->onloadTrack = (int) $tr->doc_id;
339 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
340 $this->AddEvent("ERROR-L", false, "Key Expired");
341 return "Key Expired";
343 // user logged in and not
344 $au = $this->getAuthUser();
345 if ($au && $au->id && $au->id != $tr->person_id) {
348 return "Logged Out existing Session\n - reload to log in with correct key";
350 if ($au) { // logged in anyway..
351 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
352 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
357 // authenticate the user...
359 $u = DB_DataObject::factory('Person');
361 $u->get($tr->person_id);
363 $this->AddEvent("LOGIN", false, "With Key");
365 // we need to redirect out - otherwise refererer url will include key!
366 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
378 * ------------- Authentication password reset ------ ??? MOVEME?
384 function resetPassword($id,$t, $key)
387 $au = $this->getAuthUser();
389 return "Already Logged in - no need to use Password Reset";
392 $u = DB_DataObject::factory('Person');
393 //$u->company_id = $this->company->id;
395 if (!$u->get($id) || !strlen($u->passwd)) {
400 if ($key != $u->genPassKey($t)) {
401 return "invalid key";
404 $u->no_reset_sent = 0;
407 if ($t < strtotime("NOW - 1 DAY")) {
410 $this->showNewPass = implode("/", array($id,$t,$key));
416 * ---------------- Standard JSON outputers. - used everywhere
419 function jerr($str, $errors=array()) // standard error reporting..
421 require_once 'Services/JSON.php';
422 $json = new Services_JSON();
425 $this->addEvent("ERROR", false, $str);
427 if (!empty($_REQUEST['returnHTML']) ||
428 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
430 header('Content-type: text/html');
431 echo "<HTML><HEAD></HEAD><BODY>";
432 echo $json->encodeUnsafe(array(
435 'message' => $str, // compate with exeption / loadexception.
437 'errors' => $errors ? $errors : true, // used by forms to flag errors.
438 'authFailure' => !empty($errors['authFailure']),
440 echo "</BODY></HTML>";
444 echo $json->encode(array(
448 'message' => $str, // compate with exeption / loadexception.
449 'errors' => $errors ? $errors : true, // used by forms to flag errors.
450 'authFailure' => !empty($errors['authFailure']),
458 require_once 'Services/JSON.php';
459 $json = new Services_JSON();
461 if (!empty($_REQUEST['returnHTML']) ||
462 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
465 header('Content-type: text/html');
466 echo "<HTML><HEAD></HEAD><BODY>";
467 // encode html characters so they can be read..
468 echo str_replace(array('<','>'), array('\u003c','\u003e'),
469 $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
470 echo "</BODY></HTML>";
475 echo $json->encode(array('success'=> true, 'data' => $str));
480 * output data for grids or tree
481 * @ar {Array} ar Array of data
482 * @total {Number|false} total number of records (or false to return count(ar)
483 * @extra {Array} extra key value list of data to pass as extra data.
486 function jdata($ar,$total=false, $extra=array())
488 // should do mobile checking???
489 if ($total == false) {
492 $extra= $extra ? $extra : array();
493 require_once 'Services/JSON.php';
494 $json = new Services_JSON();
495 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
506 * ---------------- Page output?!?!?
510 function hasBg($fn) // used on front page to check if logos exist..
512 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
515 function outputJavascriptIncludes() // includes on devel version..
518 $mods = explode(',', $this->appModules);
519 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
520 array_unshift($mods, 'Core');
523 $mods = array_unique($mods);
525 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
527 foreach($mods as $mod) {
528 // add the css file..
529 if (in_array($mod, $disabled)) {
534 $files = $this->moduleJavascriptList($mod.'/widgets');
535 foreach($files as $f) {
536 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
539 $files = $this->moduleJavascriptList($mod);
540 foreach($files as $f) {
541 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
548 function outputCSSIncludes() // includes on CSS links.
551 $mods = explode(',', $this->appModules);
552 array_unshift($mods, 'Core');
553 $mods = array_unique($mods);
555 foreach($mods as $mod) {
556 // add the css file..
557 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
558 if (file_exists( $css)){
559 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
560 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
571 function moduleJavascriptList($mod)
574 $ff = HTML_FlexyFramework::get();
576 $dir = $this->rootDir.'/Pman/'. $mod;
578 $path = $this->rootURL."/Pman/$mod/";
579 $base = dirname($_SERVER['SCRIPT_FILENAME']);
580 $cfile = realpath($base .'/_compiled_/' . $mod);
581 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
583 if (!file_exists($dir)) {
591 if (file_exists($cfile)) {
592 // $ctime = max(filemtime($cfile), filectime($cfile));
593 // otherwise use compile dfile..
595 $ar = glob($cfile . '/' . $mod . '*.js');
596 // default to first..
597 $cfile = basename($ar[count($ar) -1]);
598 foreach($ar as $fn) {
599 if (filemtime($fn) > $maxm) {
600 $cfile = basename($fn);
601 $maxm = filemtime($fn);
607 $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
608 if (file_exists($lfile)) {
609 array_push($files, $this->rootURL."/_translations_/$mod.js");
613 // works out if stuff has been updated..
614 // technically the non-dev version should output compiled only?!!?
616 while (false !== ($f = readdir($dh))) {
618 if (!preg_match('/\.js$/', $f)) {
621 // got the 'module file..'
623 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
624 $files[] = $path . $f;
629 // var_dump(array($maxtime , $ctime));
630 //if ($maxtime > $ctime) {
631 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
632 usort($files, $lsort);
633 // if (file_exists($lfile)) {
634 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
645 * ---------------- Logging ---------------
650 * Log an action (only if it has not been logged already.
652 * @param {String} action - group/name of event
653 * @param {DataObject|false} obj - dataobject action occured on.
654 * @param {String} any remarks
657 function addEventOnce($act, $obj = false, $remarks = '')
659 $au = $this->getAuthUser();
660 $e = DB_DataObject::factory('Events');
661 $e->init($act,$obj,$remarks);
662 if ($e->find(true)) {
665 $this->addEvent($act, $obj, $remarks);
671 * @param {String} action - group/name of event
672 * @param {DataObject|false} obj - dataobject action occured on.
673 * @param {String} any remarks
674 * @return {Number} id of event created.
677 function addEvent($act, $obj = false, $remarks = '')
679 $au = $this->getAuthUser();
680 $e = DB_DataObject::factory('Events');
681 $e->init($act,$obj,$remarks);
683 $e->event_when = date('Y-m-d H:i:s');
686 $ff = HTML_FlexyFramework::get();
687 if (empty($ff->Pman['event_log_dir'])) {
690 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
691 if (!file_exists(dirname($file))) {
692 mkdir(dirname($file),0700,true);
694 file_put_contents($file, var_export(array(
695 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
696 'GET' => empty($_GET) ? array() : $_GET,
697 'POST' => empty($_POST) ? array() : $_POST,