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
28 var $appShortName= "";
29 var $appVersion = "1.8";
36 var $appDisabled = array(); // array of disabled modules..
37 // (based on config option disable)
39 var $authUser; // always contains the authenticated user..
44 * ------------- Standard getAuth/get/post methods of framework.
49 function getAuth() // everyone allowed in!!!!!
51 $this->loadOwnerCompany();
59 if (isset($this->_hasInit)) {
62 $this->_hasInit = true;
64 $boot = HTML_FlexyFramework::get();
65 // echo'<PRE>';print_R($boot);exit;
66 $this->appName= $boot->appName;
67 $this->appNameShort= $boot->appNameShort;
70 $this->appModules= $boot->enable;
71 $this->isDev = empty($boot->Pman['isDev']) ? false : $boot->Pman['isDev'];
72 $this->appDisable = $boot->disable;
73 $this->appDisabled = explode(',', $boot->disable);
74 $this->version = $boot->version;
76 if (!empty($ff->Pman['local_autoauth']) &&
77 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
78 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
91 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
92 $bits = explode('/', $base);
94 if ($bits[0] == 'Link') {
95 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
96 header('Content-type: text/html; charset=utf-8');
99 if ($bits[0] == 'PasswordReset') {
100 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
101 header('Content-type: text/html; charset=utf-8');
106 if ($this->getAuthUser()) {
107 $this->addEvent("RELOAD");
112 $this->addEvent("BADURL", false, $base);
113 $this->jerr("invalid url");
116 if (isset($_GET['onloadTrack'])) {
117 $this->onloadTrack = (int)$_GET['onloadTrack'];
119 // getting this to work with xhtml is a nightmare
120 // = nbsp / <img> issues screw everyting up.
121 //var_dump($this->isDev);
122 // force regeneration on load for development enviroments..
124 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
126 //header('Content-type: application/xhtml+xml; charset=utf-8');
130 if ($this->company->logo_id) {
131 $im = DB_DataObject::Factory('Images');
132 $im->get($this->company->logo_id);
133 $this->appLogo = $this->baseURL . '/Images/Thumb/300x100/'. $this->company->logo_id .'/' . $im->filename;
136 header('Content-type: text/html; charset=utf-8');
139 function post($base) {
140 return $this->get($base);
144 // --------------- AUTHENTICATION or system information
147 * finds the compay with comptype=='OWNER'
149 * @return {Pman_Core_DataObjects_Companies} the owner company
151 function loadOwnerCompany()
154 $this->company = DB_DataObject::Factory('Companies');
155 if (!is_a($this->company, 'DB_DataObject')) { // non-core pman projects
158 $this->company->get('comptype', 'OWNER');
159 return $this->company;
165 * getAuthUser: - get the authenticated user..
167 * @return {DB_DataObject} of type Pman[authTable] if authenticated.
170 function getAuthUser()
172 if (!empty($this->authUser)) {
173 return $this->authUser;
175 $ff = HTML_FlexyFramework::get();
176 $tbl = empty($ff->Pman['authTable']) ? 'Person' : $ff->Pman['authTable'];
178 $u = DB_DataObject::factory( $tbl );
182 $this->authUser =$u->getAuthUser();
183 return $this->authUser ;
187 * wrapper arround authuser->hasPerm
188 * @see Pman_Core_DataObjects_User::hasPerm
190 * @param {String} $name The permission name (eg. Projects.List)
191 * @param {String} $lvl eg. (C)reate (E)dit (D)elete ... etc.
194 function hasPerm($name, $lvl) // do we have a permission
196 static $pcache = array();
197 $au = $this->getAuthUser();
198 return $au && $au->hasPerm($name,$lvl);
203 * modulesList: List the modules in the application
205 * @return {Array} list of modules
207 function modulesList()
211 $mods = explode(',', $this->appModules);
212 if (in_array('Core',$mods)) { // core has to be the first modules loaded as it contains Pman.js
213 array_unshift($mods, 'Core');
216 $mods = array_unique($mods);
218 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
220 foreach($mods as $mod) {
221 // add the css file..
222 if (in_array($mod, $disabled)) {
233 function hasModule($name)
236 if (!strpos( $name,'.') ) {
237 // use enable / disable..
238 return in_array($name, $this->modules());
241 $x = DB_DataObject::factory('Group_Rights');
242 $ar = $x->defaultPermData();
243 if (empty($ar[$name]) || empty($ar[$name][0])) {
254 * ---------------- Global Tools ---------------
260 * send a template to the user
261 * rcpts are read from the resulting template.
263 * @arg $templateFile - the file in mail/XXXXXX.txt
264 * @arg $args - variables available to the form as {t.*} over and above 'this'
269 function sendTemplate($templateFile, $args)
274 $content = clone($this);
276 foreach((array)$args as $k=>$v) {
279 $content->msgid = md5(time() . rand());
281 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
282 /* use the regex compiler, as it doesnt parse <tags */
283 require_once 'HTML/Template/Flexy.php';
284 $template = new HTML_Template_Flexy( array(
285 'compiler' => 'Regex',
286 'filters' => array('SimpleTags','Mail'),
290 // this should be done by having multiple template sources...!!!
292 $template->compile('mail/'. $templateFile.'.txt');
294 /* use variables from this object to ouput data. */
295 $mailtext = $template->bufferedOutputObject($content);
296 //echo "<PRE>";print_R($mailtext);
298 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
299 require_once 'Mail/mimeDecode.php';
300 require_once 'Mail.php';
302 $decoder = new Mail_mimeDecode($mailtext);
303 $parts = $decoder->getSendArray();
304 if (PEAR::isError($parts)) {
306 //echo "PROBLEM: {$parts->message}";
309 list($recipents,$headers,$body) = $parts;
310 ///$recipents = array($this->email);
311 $mailOptions = PEAR::getStaticProperty('Mail','options');
312 $mail = Mail::factory("SMTP",$mailOptions);
313 $headers['Date'] = date('r');
314 if (PEAR::isError($mail)) {
317 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
318 $ret = $mail->send($recipents,$headers,$body);
319 error_reporting($oe);
325 function checkFileUploadError() // check for file upload errors.
328 empty($_FILES['File'])
329 || empty($_FILES['File']['name'])
330 || empty($_FILES['File']['tmp_name'])
331 || empty($_FILES['File']['type'])
332 || !empty($_FILES['File']['error'])
333 || empty($_FILES['File']['size'])
335 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
341 * generate a tempory file with an extension (dont forget to delete it)
344 function tempName($ext)
346 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
348 return $x .'.'. $ext;
351 * ------------- Authentication testing ------ ??? MOVEME?
355 function linkAuth($trid, $trkey)
357 $tr = DB_DataObject::factory('Documents_Tracking');
358 if (!$tr->get($trid)) {
359 return "Invalid URL";
361 if (strtolower($tr->authkey) != strtolower($trkey)) {
362 $this->AddEvent("ERROR-L", false, "Invalid Key");
363 return "Invalid KEY";
366 $this->onloadTrack = (int) $tr->doc_id;
367 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
368 $this->AddEvent("ERROR-L", false, "Key Expired");
369 return "Key Expired";
371 // user logged in and not
372 $au = $this->getAuthUser();
373 if ($au && $au->id && $au->id != $tr->person_id) {
376 return "Logged Out existing Session\n - reload to log in with correct key";
378 if ($au) { // logged in anyway..
379 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
380 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
385 // authenticate the user...
387 $u = DB_DataObject::factory('Person');
389 $u->get($tr->person_id);
391 $this->AddEvent("LOGIN", false, "With Key");
393 // we need to redirect out - otherwise refererer url will include key!
394 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
406 * ------------- Authentication password reset ------ ??? MOVEME?
412 function resetPassword($id,$t, $key)
415 $au = $this->getAuthUser();
417 return "Already Logged in - no need to use Password Reset";
420 $u = DB_DataObject::factory('Person');
421 //$u->company_id = $this->company->id;
423 if (!$u->get($id) || !strlen($u->passwd)) {
428 if ($key != $u->genPassKey($t)) {
429 return "invalid key";
432 $u->no_reset_sent = 0;
435 if ($t < strtotime("NOW - 1 DAY")) {
438 $this->showNewPass = implode("/", array($id,$t,$key));
443 * jerrAuth: standard auth failure - with data that let's the UI know..
447 $au = $this->authUser();
449 // is it an authfailure?
450 $this->jerr("Permission denied to view this resource", array('authFailure' => true));
452 $this->jerr("Not authenticated", array('authFailure' => true));
458 * ---------------- Standard JSON outputers. - used everywhere
461 function jerr($str, $errors=array()) // standard error reporting..
464 $cli = HTML_FlexyFramework::get()->cli;
466 echo "ERROR: " .$str . "\n";
470 require_once 'Services/JSON.php';
471 $json = new Services_JSON();
474 $this->addEvent("ERROR", false, $str);
476 if (!empty($_REQUEST['returnHTML']) ||
477 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
479 header('Content-type: text/html');
480 echo "<HTML><HEAD></HEAD><BODY>";
481 echo $json->encodeUnsafe(array(
484 'message' => $str, // compate with exeption / loadexception.
486 'errors' => $errors ? $errors : true, // used by forms to flag errors.
487 'authFailure' => !empty($errors['authFailure']),
489 echo "</BODY></HTML>";
493 echo $json->encode(array(
497 'message' => $str, // compate with exeption / loadexception.
498 'errors' => $errors ? $errors : true, // used by forms to flag errors.
499 'authFailure' => !empty($errors['authFailure']),
507 $cli = HTML_FlexyFramework::get()->cli;
509 echo "OK: " .$str . "\n";
512 require_once 'Services/JSON.php';
513 $json = new Services_JSON();
515 if (!empty($_REQUEST['returnHTML']) ||
516 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
519 header('Content-type: text/html');
520 echo "<HTML><HEAD></HEAD><BODY>";
521 // encode html characters so they can be read..
522 echo str_replace(array('<','>'), array('\u003c','\u003e'),
523 $json->encodeUnsafe(array('success'=> true, 'data' => $str)));
524 echo "</BODY></HTML>";
529 echo $json->encode(array('success'=> true, 'data' => $str));
535 * output data for grids or tree
536 * @ar {Array} ar Array of data
537 * @total {Number|false} total number of records (or false to return count(ar)
538 * @extra {Array} extra key value list of data to pass as extra data.
541 function jdata($ar,$total=false, $extra=array())
543 // should do mobile checking???
544 if ($total == false) {
547 $extra= $extra ? $extra : array();
548 require_once 'Services/JSON.php';
549 $json = new Services_JSON();
550 if (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE'])) {
552 header('Content-type: text/html');
553 echo "<HTML><HEAD></HEAD><BODY>";
554 // encode html characters so they can be read..
555 echo str_replace(array('<','>'), array('\u003c','\u003e'),
556 $json->encodeUnsafe(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra));
557 echo "</BODY></HTML>";
567 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
577 * ---------------- OUTPUT
579 function hasBg($fn) // used on front page to check if logos exist..
581 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
584 * outputJavascriptIncludes:
586 * output <script....> for all the modules in the applcaiton
589 function outputJavascriptIncludes()
592 $mods = $this->modulesList();
594 foreach($mods as $mod) {
595 // add the css file..
598 $files = $this->moduleJavascriptList($mod.'/widgets');
599 foreach($files as $f) {
600 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
603 $files = $this->moduleJavascriptList($mod);
604 foreach($files as $f) {
605 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
609 // and finally the JsTemplate...
610 echo '<script type="text/javascript" src="'. $this->baseURL. '/Core/JsTemplate"></script>'."\n";
616 * output <link rel=stylesheet......> for all the modules in the applcaiton
619 * This could css minify as well.
621 function outputCSSIncludes() // includes on CSS links.
624 $mods = $this->modulesList();
627 foreach($mods as $mod) {
628 // add the css file..
629 $dir = $this->rootDir.'/Pman/'.$mod;
630 $ar = glob($dir . '/*.css');
631 foreach($ar as $fn) {
632 $css = $this->rootURL .'/Pman/'.$mod.'/'.basename($fn);
633 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
642 * Gather infor for javascript files..
644 * @param {String} $mod the module to get info about.
645 * @return {StdClass} details about module.
647 function moduleJavascriptFilesInfo($mod)
650 static $cache = array();
652 if (isset($cache[$mod])) {
657 $ff = HTML_FlexyFramework::get();
659 $base = dirname($_SERVER['SCRIPT_FILENAME']);
660 $dir = $this->rootDir.'/Pman/'. $mod;
661 $path = $this->rootURL ."/Pman/$mod/";
663 $ar = glob($dir . '/*.js');
669 foreach($ar as $fn) {
671 // got the 'module file..'
672 $mtime = filemtime($dir . '/'. $f);
673 $maxtime = max($mtime, $maxtime);
674 $arfiles[$fn] = $mtime;
675 $files[] = $path . $f . '?ts='.$mtime;
678 ksort($arfiles); // just sort by name so it's consistant for serialize..
680 $compile = empty($ff->Pman['public_cache_dir']) ? 0 : 1;
681 $basedir = $ff->Pman['public_cache_dir'];
682 $baseurl = $ff->Pman['public_cache_url'];
684 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
685 usort($files, $lsort);
687 $smod = str_replace('/','.',$mod);
689 $output = date('Y-m-d-H-i-s-', $maxtime). $smod .'-'.md5(serialize($arfiles)) .'.js';
691 $tmtime = file_exists($this->rootDir.'/_translations_/'. $smod.'.js')
692 ? filemtime($this->rootDir.'/_translations_/'. $smod.'.js') : 0;
694 $cache[$mod] = (object) array(
695 'smod' => $smod, // module name without '/'
696 'files' => $files, // list of all files.
697 'filesmtime' => $arfiles, // map of mtime=>file
698 'maxtime' => $maxtime, // max mtime
699 'compile' => $this->isDev ? false : $compile,
700 'translation_file' => $base .'/_translations_/' . $smod . '.js',
701 'translation_mtime' => $tmtime,
703 'translation_data' => preg_replace('/\.js$/', '.__translation__.js', $output),
704 'translation_base' => $dir .'/', //prefix of filename (without moudle name))
705 'basedir' => $basedir,
706 'baseurl' => $baseurl,
707 'module_dir' => $dir,
714 * moduleJavascriptList: list the javascript files in a module
716 * The original version of this.. still needs more thought...
718 * Compiled is in Pman/_compiled_/{$mod}/{LATEST...}.js
719 * Translations are in Pman/_translations_/{$mod}.js
721 * if that stuff does not exist just list files in Pman/{$mod}/*.js
723 * Compiled could be done on the fly..
727 * @param {String} $mod the module to look at - eg. Pman/{$mod}/*.js
728 * @return {Array} list of include paths (either compiled or raw)
734 function moduleJavascriptList($mod)
738 $dir = $this->rootDir.'/Pman/'. $mod;
741 if (!file_exists($dir)) {
742 echo '<!-- missing directory '. htmlspecialchars($dir) .' -->';
746 $info = $this->moduleJavascriptFilesInfo($mod);
750 if (empty($info->files)) {
753 // finally sort the files, so they are in the right order..
755 // only compile this stuff if public_cache is set..
759 // public_cache_dir = /var/www/myproject_cache
760 // public_cache_url = /myproject_cache (with Alias apache /myproject_cache/ /var/www/myproject_cache/)
763 if (!$info->compile) {
764 echo "<!-- Javascript compile turned off (isDev on, or public_cache_dir not set) -->\n";
767 // where are we going to write all of this..
768 // This has to be done via a
769 if (!file_exists($info->basedir.'/'.$info->output)) {
770 require_once 'Pman/Core/JsCompile.php';
771 $x = new Pman_Core_JsCompile();
773 $x->pack($info->filesmtime,$info->basedir.'/'.$info->output, $info->translation_base);
776 if (file_exists($info->basedir.'/'.$info->output) &&
777 filesize($info->basedir.'/'.$info->output)) {
780 $info->baseurl.'/'. $info->output,
783 if ($info->translation_mtime) {
784 $ret[] = $this->rootURL."/_translations_/". $info->smod.".js?ts=".$info->translation_mtime;
791 // give up and output original files...
802 * ---------------- Logging ---------------
807 * Log an action (only if it has not been logged already.
809 * @param {String} action - group/name of event
810 * @param {DataObject|false} obj - dataobject action occured on.
811 * @param {String} any remarks
812 * @return {false|DB_DataObject} Event object.,
815 function addEventOnce($act, $obj = false, $remarks = '')
818 $e = DB_DataObject::factory('Events');
819 $e->init($act,$obj,$remarks);
820 if ($e->find(true)) {
823 return $this->addEvent($act, $obj, $remarks);
829 * @param {String} action - group/name of event
830 * @param {DataObject|false} obj - dataobject action occured on.
831 * @param {String} any remarks
832 * @return {DB_DataObject} Event object.,
835 function addEvent($act, $obj = false, $remarks = '')
837 $au = $this->getAuthUser();
839 $e = DB_DataObject::factory('Events');
840 $e->init($act,$obj,$remarks);
842 $e->event_when = date('Y-m-d H:i:s');
846 $wa = DB_DataObject::factory('core_watch');
847 $wa->notifyEvent($e); // trigger any actions..
850 $ff = HTML_FlexyFramework::get();
851 if (empty($ff->Pman['event_log_dir'])) {
854 $file = $ff->Pman['event_log_dir']. date('/Y/m/d/'). $eid . ".php";
855 if (!file_exists(dirname($file))) {
856 mkdir(dirname($file),0700,true);
858 // Remove all the password from logs...
859 $p = empty($_POST) ? array() : $_POST;
860 foreach(array('passwd', 'password', 'passwd2', 'password2') as $rm) {
861 if (isset($p[$rm])) {
862 $p['passwd'] = '******';
866 file_put_contents($file, var_export(array(
867 'REQUEST_URI' => empty($_SERVER['REQUEST_URI']) ? 'cli' : $_SERVER['REQUEST_URI'],
868 'GET' => empty($_GET) ? array() : $_GET,
875 // ------------------ DEPERCIATED ---
877 function modules() // DEPRECITAED
879 return $this->modulesList();
881 function staticGetAuthUser() // DEPRECIATED..
885 return $x->getAuthUser();