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);
172 function hasModule($name)
175 if (!strpos( $name,'.') ) {
176 // use enable / disable..
179 $enabled = array('Core') ;
180 $enabled = !empty($this->appModules) ?
181 array_merge($enabled, explode(',', $this->appModules)) :
183 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
187 return in_array($name, $enabled) && !in_array($name, $disabled);
190 $x = DB_DataObject::factory('Group_Rights');
191 $ar = $x->defaultPermData();
192 if (empty($ar[$name]) || empty($ar[$name][0])) {
202 * ---------------- Global Tools ---------------
208 * send a template to the user
209 * rcpts are read from the resulting template.
211 * @arg $templateFile - the file in mail/XXXXXX.txt
212 * @arg $args - variables available to the form as {t.*} over and above 'this'
217 function sendTemplate($templateFile, $args)
222 $content = clone($this);
224 foreach((array)$args as $k=>$v) {
227 $content->msgid = md5(time() . rand());
229 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
230 /* use the regex compiler, as it doesnt parse <tags */
231 require_once 'HTML/Template/Flexy.php';
232 $template = new HTML_Template_Flexy( array(
233 'compiler' => 'Regex',
234 'filters' => array('SimpleTags','Mail'),
238 // this should be done by having multiple template sources...!!!
240 $template->compile('mail/'. $templateFile.'.txt');
242 /* use variables from this object to ouput data. */
243 $mailtext = $template->bufferedOutputObject($content);
244 //echo "<PRE>";print_R($mailtext);
246 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
247 require_once 'Mail/mimeDecode.php';
248 require_once 'Mail.php';
250 $decoder = new Mail_mimeDecode($mailtext);
251 $parts = $decoder->getSendArray();
252 if (PEAR::isError($parts)) {
254 //echo "PROBLEM: {$parts->message}";
257 list($recipents,$headers,$body) = $parts;
258 ///$recipents = array($this->email);
259 $mailOptions = PEAR::getStaticProperty('Mail','options');
260 $mail = Mail::factory("SMTP",$mailOptions);
261 $headers['Date'] = date('r');
262 if (PEAR::isError($mail)) {
265 $oe = error_reporting(E_ALL ^ E_NOTICE);
266 $ret = $mail->send($recipents,$headers,$body);
267 error_reporting($oe);
273 function checkFileUploadError() // check for file upload errors.
276 empty($_FILES['File'])
277 || empty($_FILES['File']['name'])
278 || empty($_FILES['File']['tmp_name'])
279 || empty($_FILES['File']['type'])
280 || !empty($_FILES['File']['error'])
281 || empty($_FILES['File']['size'])
283 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
289 * generate a tempory file with an extension (dont forget to delete it)
292 function tempName($ext)
294 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
296 return $x .'.'. $ext;
299 * ------------- Authentication testing ------ ??? MOVEME?
303 function linkAuth($trid, $trkey)
305 $tr = DB_DataObject::factory('Documents_Tracking');
306 if (!$tr->get($trid)) {
307 return "Invalid URL";
309 if (strtolower($tr->authkey) != strtolower($trkey)) {
310 $this->AddEvent("ERROR-L", false, "Invalid Key");
311 return "Invalid KEY";
314 $this->onloadTrack = (int) $tr->doc_id;
315 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
316 $this->AddEvent("ERROR-L", false, "Key Expired");
317 return "Key Expired";
319 // user logged in and not
320 $au = $this->getAuthUser();
321 if ($au && $au->id && $au->id != $tr->person_id) {
324 return "Logged Out existing Session\n - reload to log in with correct key";
326 if ($au) { // logged in anyway..
327 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
328 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
333 // authenticate the user...
335 $u = DB_DataObject::factory('Person');
337 $u->get($tr->person_id);
339 $this->AddEvent("LOGIN", false, "With Key");
341 // we need to redirect out - otherwise refererer url will include key!
342 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
354 * ------------- Authentication password reset ------ ??? MOVEME?
360 function resetPassword($id,$t, $key)
363 $au = $this->getAuthUser();
365 return "Already Logged in - no need to use Password Reset";
368 $u = DB_DataObject::factory('Person');
369 //$u->company_id = $this->company->id;
371 if (!$u->get($id) || !strlen($u->passwd)) {
376 if ($key != $u->genPassKey($t)) {
377 return "invalid key";
380 $u->no_reset_sent = 0;
383 if ($t < strtotime("NOW - 1 DAY")) {
386 $this->showNewPass = implode("/", array($id,$t,$key));
392 * ---------------- Standard JSON outputers. - used everywhere
395 function jerr($str, $errors=array()) // standard error reporting..
397 require_once 'Services/JSON.php';
398 $json = new Services_JSON();
401 $this->addEvent("ERROR", false, $str);
403 if (!empty($_REQUEST['returnHTML']) ||
404 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
406 header('Content-type: text/html');
407 echo "<HTML><HEAD></HEAD><BODY>";
408 echo $json->encodeUnsafe(array(
411 'message' => $str, // compate with exeption / loadexception.
413 'errors' => $errors ? $errors : true, // used by forms to flag errors.
414 'authFailure' => !empty($errors['authFailure']),
416 echo "</BODY></HTML>";
420 echo $json->encode(array(
424 'message' => $str, // compate with exeption / loadexception.
425 'errors' => $errors ? $errors : true, // used by forms to flag errors.
426 'authFailure' => !empty($errors['authFailure']),
434 require_once 'Services/JSON.php';
435 $json = new Services_JSON();
437 if (!empty($_REQUEST['returnHTML']) ||
438 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
441 header('Content-type: text/html');
442 echo "<HTML><HEAD></HEAD><BODY>";
443 echo $json->encodeUnsafe(array('success'=> true, 'data' => $str));
444 echo "</BODY></HTML>";
449 echo $json->encode(array('success'=> true, 'data' => $str));
454 * output data for grids or tree
455 * @ar {Array} ar Array of data
456 * @total {Number|false} total number of records (or false to return count(ar)
457 * @extra {Array} extra key value list of data to pass as extra data.
460 function jdata($ar,$total=false, $extra=array())
462 // should do mobile checking???
463 if ($total == false) {
466 $extra= $extra ? $extra : array();
467 require_once 'Services/JSON.php';
468 $json = new Services_JSON();
469 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
480 * ---------------- Page output?!?!?
484 function hasBg($fn) // used on front page to check if logos exist..
486 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
489 function outputJavascriptIncludes() // includes on devel version..
492 $mods = explode(',', $this->appModules);
493 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
494 array_unshift($mods, 'Core');
497 $mods = array_unique($mods);
499 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
501 foreach($mods as $mod) {
502 // add the css file..
503 if (in_array($mod, $disabled)) {
508 $files = $this->moduleJavascriptList($mod.'/widgets');
509 foreach($files as $f) {
510 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
513 $files = $this->moduleJavascriptList($mod);
514 foreach($files as $f) {
515 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
522 function outputCSSIncludes() // includes on CSS links.
525 $mods = explode(',', $this->appModules);
526 array_unshift($mods, 'Core');
527 $mods = array_unique($mods);
529 foreach($mods as $mod) {
530 // add the css file..
531 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
532 if (file_exists( $css)){
533 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
534 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
545 function moduleJavascriptList($mod)
548 $ff = HTML_FlexyFramework::get();
550 $dir = $this->rootDir.'/Pman/'. $mod;
552 $path = $this->rootURL."/Pman/$mod/";
553 $base = dirname($_SERVER['SCRIPT_FILENAME']);
554 $cfile = realpath($base .'/_compiled_/' . $mod);
555 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
557 if (!file_exists($dir)) {
565 if (file_exists($cfile)) {
566 // $ctime = max(filemtime($cfile), filectime($cfile));
567 // otherwise use compile dfile..
569 $ar = glob($cfile . '/' . $mod . '*.js');
570 // default to first..
571 $cfile = basename($ar[count($ar) -1]);
572 foreach($ar as $fn) {
573 if (filemtime($fn) > $maxm) {
574 $cfile = basename($fn);
575 $maxm = filemtime($fn);
581 $files = array( $this->rootURL. "/_compiled_/".$mod . "/" . $cfile);
582 if (file_exists($lfile)) {
583 array_push($files, $this->rootURL."/_translations_/$mod.js");
587 // works out if stuff has been updated..
588 // technically the non-dev version should output compiled only?!!?
590 while (false !== ($f = readdir($dh))) {
592 if (!preg_match('/\.js$/', $f)) {
595 // got the 'module file..'
597 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
598 $files[] = $path . $f;
603 // var_dump(array($maxtime , $ctime));
604 //if ($maxtime > $ctime) {
605 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
606 usort($files, $lsort);
607 // if (file_exists($lfile)) {
608 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
619 * ---------------- Logging ---------------
624 * Log an action (only if it has not been logged already.
626 * @param {String} action - group/name of event
627 * @param {DataObject|false} obj - dataobject action occured on.
628 * @param {String} any remarks
631 function addEventOnce($act, $obj = false, $remarks = '')
633 $au = $this->getAuthUser();
634 $e = DB_DataObject::factory('Events');
635 $e->init($act,$obj,$remarks);
636 if ($e->find(true)) {
639 $this->addEvent($act, $obj, $remarks);
645 * @param {String} action - group/name of event
646 * @param {DataObject|false} obj - dataobject action occured on.
647 * @param {String} any remarks
650 function addEvent($act, $obj = false, $remarks = '')
652 $au = $this->getAuthUser();
653 $e = DB_DataObject::factory('Events');
654 $e->init($act,$obj,$remarks);
656 $e->event_when = date('Y-m-d H:i:s');
659 $ff = HTML_FlexyFramework::get();
660 if (empty($ff->Pman['event_log_dir'])) {
663 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
664 if (!file_exists(dirname($file))) {
665 mkdir(dirname($file),0700,true);
667 file_put_contents($file, var_export(array(
668 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
669 'GET' => empty($_GET) ? array() : $_GET,
670 'POST' => empty($_POST) ? array() : $_POST,