DataObjects/Core_company.php
[Pman.Core] / DataObjects / Core_company.php
1 <?php
2 /**
3  * Table Definition for Companies
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_Company extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'core_company';                       // table name
13     public $code;                            // string(32)  not_null
14     public $name;                            // string(128)  
15     public $remarks;                         // blob(65535)  blob
16     public $owner_id;                        // int(11)  not_null
17     public $address;                         // blob(65535)  blob
18     public $tel;                             // string(32)  
19     public $fax;                             // string(32)  
20     public $email;                           // string(128)  
21     public $id;                              // int(11)  not_null primary_key auto_increment
22     public $isOwner;                         // int(11)  
23     public $logo_id;                         // int(11)  not_null
24     public $background_color;                // string(8)  not_null
25     public $comptype;                        // string(8)  not_null
26     public $url;                             // string(254)  not_null
27     public $main_office_id;                  // int(11)  not_null
28     public $created_by;                      // int(11)  not_null
29     public $created_dt;                      // datetime(19)  not_null binary
30     public $updated_by;                      // int(11)  not_null
31     public $updated_dt;                      // datetime(19)  not_null binary
32     public $passwd;                          // string(64)  not_null
33     public $dispatch_port;                   // string(255)  not_null
34     public $province;                        // string(255)  not_null
35     public $country;                         // string(4)  not_null
36     public $is_system;                       // int(2)
37     
38     /* the code above is auto generated do not remove the tag below */
39     ###END_AUTOCODE
40     
41     function applyFilters($q, $au)
42     {
43         
44         $tn = $this->tableName();
45         $this->selectAdd("i18n_translate('c' , {$tn}.country, 'en') as country_display_name ");
46       
47         $tn = $this->tableName();
48         //DB_DataObject::debugLevel(1);
49         $x = DB_DataObject::factory('core_company');
50         $x->comptype= 'OWNER';
51         $x->find(true);
52
53         if (!empty($q['query']['company_project_id'])) {
54             $add = '';
55             if (!empty($q['query']['company_include_self'])) {
56                 $add = " OR {$tn}.id = {$x->id}";
57             }
58             if (!empty($q['query']['company_not_self'])) {
59                 $add = " AND {$tn}.id != {$x->id}";
60             }
61             
62             $pids = array();
63             $pid = $q['query']['company_project_id'];
64             if (strpos($pid, ',')) {
65                 $bits = explode(',', $pid);
66                 foreach($bits as $b) {
67                     $pids[] = (int)$b;
68                 }
69             } else {
70                 $pids = array($pid);
71             }
72             
73             
74             $pids = implode(',', $pids);
75             $this->whereAdd("{$tn}.id IN (
76                 SELECT distinct(company_id) FROM ProjectDirectory where project_id IN ($pids)
77             ) $add" );
78              
79         }
80         if (!empty($q['query']['comptype'])) {
81            
82             $this->whereAddIn('comptype', explode(',', $q['query']['comptype']), 'string');
83             
84         }
85         
86         // depricated - should be moved to module specific (texon afair)
87         
88          if (!empty($q['query']['province'])) {
89              $prov = $this->escape($q['query']['province']);
90             $this->whereAdd("province LIKE '$prov%'");
91             
92             
93         }
94         // ADD comptype_display name.. = for combos..
95         $this->selectAdd("
96             (SELECT display_name
97                 FROM
98                     core_enum
99                 WHERE
100                     etype='comptype'
101                     AND
102                     name={$tn}.comptype
103                 LIMIT 1
104                 ) as comptype_display_name
105         ");
106         
107         if(!empty($q['query']['name'])){
108             $s = $this->escape($q['query']['name']);
109             $this->whereAdd("
110                 {$tn}.name LIKE '%$s%'
111             ");
112         }
113         if(!empty($q['search']['name'])){ 
114             $s = $this->escape($q['search']['name']);
115             $this->whereAdd("
116                 {$tn}.name LIKE '%$s%'
117             ");
118         }
119         if(!empty($q['search']['name_starts'])){
120             $s = $this->escape($q['search']['name_starts']);
121             $this->whereAdd("
122                 {$tn}.name LIKE '$s%'
123             ");
124         }
125     }
126     
127     function toEventString() {
128         return $this->name;
129     }
130     
131     // ---------- AUTHENTICATION
132     // not sure where authetnication via company is used?? posibly media-outreach
133     
134     function isAuth()
135     {
136         $db = $this->getDatabaseConnection();
137         $sesPrefix = $db->dsn['database'];
138         @session_start();
139         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
140             // in session...
141             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
142             $u = DB_DataObject::factory('core_company');
143             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
144                 return true;
145             }
146             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
147             
148         }
149         // not in session or not matched...
150         
151         
152         return false;
153         
154     }
155     function getAuthUser()
156     {
157         if (!$this->isAuth()) {
158             return false;
159         }
160         $db = $this->getDatabaseConnection();
161         $sesPrefix = $db->dsn['database'];
162         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
163             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
164             
165             $u = DB_DataObject::factory('core_company');
166             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
167                 return clone($u);
168             }
169              
170         }
171         
172         
173         return false;
174     }     
175     function login()
176     {
177         $this->isAuth(); // force session start..
178          $db = $this->getDatabaseConnection();
179         $sesPrefix = $db->dsn['database'];
180         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
181         
182     }
183     function logout()
184     {
185         $this->isAuth(); // force session start..
186         $db = $this->getDatabaseConnection();
187         $sesPrefix = $db->dsn['database'];
188         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
189         
190     }    
191     // ---------- AUTHENTICATION
192     function checkPassword($val)
193     {
194         //echo '<pre>'.$val .  print_R($this,true);
195         if (substr($this->passwd,0,1) == '$') {
196             return crypt($val,$this->passwd) == $this->passwd ;
197         }
198         // old style md5 passwords...- cant be used with courier....
199         return md5($val) == $this->passwd;
200     }
201     function setPassword($value) 
202     {
203         $salt='';
204         while(strlen($salt)<9) {
205             $salt.=chr(rand(64,126));
206             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
207         }
208         $this->passwd = crypt($value, '$1$'. $salt. '$');
209        
210     }      
211     function onUpload($controller)
212     {
213         $image = DB_DataObject::factory('Images');
214         return $image->onUploadWithTbl($this, 'logo_id');
215          
216     }
217     function  onUpdate($old, $req,$roo) 
218     {
219         if (!empty($req['password1'])) {
220             $this->setPassword($req['password1']);
221             $this->update();
222         }
223     }
224     function onInsert($req, $roo)
225     {
226         if (!empty($this->logo_id)) { // update images table to sycn with this..
227             $img = DB_DataObject::factory('Images');
228             if ($img->get($this->logo_id) && ($img->onid != $this->id)) {
229                 $img->onid = $this->id;
230                 $img->update();
231             }
232         }
233         if (!empty($req['password1'])) {
234             $this->setPassword($req['password1']);
235             $this->update();
236         }
237         $img = DB_DataObject::factory('Images');
238         $img->onid= 0;
239         
240         $img->ontable = $this->tableName();
241         $img->imgtype = 'LOGO';
242         // should check uploader!!!
243         if ($img->find()) {
244             while($img->fetch()) {
245                 $ii = clone($img);
246                 $ii->onid = $this->id;
247                 $ii->update();
248                 $this->logo_id = $ii->id;
249             }
250             $this->update();
251         }
252         
253     }
254     
255     function beforeInsert($q, $roo)
256     {
257         // we still use comptype in some old systems...
258         
259         if (!empty($q['comptype_id'])) {
260             $en = DB_DataObject::Factory('core_enum');
261             $en->get($q['comptype_id']);
262             $this->comptype = $en->name;
263         }
264         
265         if(!empty($q['_check_name'])){
266             if($this->checkName()){
267                 $roo->jok('OK');
268             }
269             
270             $roo->jerr('EXIST');
271         }
272     }
273     
274     function beforeUpdate($old, $q,$roo)
275     {
276         // we still use comptype in some old systems...
277         
278         if (!empty($q['comptype_id'])) {
279             $en = DB_DataObject::Factory('core_enum');
280             $en->get($q['comptype_id']);
281             $this->comptype = $en->name;
282         }
283         
284         
285         if(!empty($q['_flag_delete'])){
286             $this->deleted_dt = $this->sqlValue("NOW()");
287             $this->deleted_by = $roo->getAuthUser()->id;
288         }
289         
290         if(!empty($q['_flag_undelete'])){
291             $this->deleted_dt = "";
292             $this->deleted_by = 0;
293         }
294         if(!empty($q['_check_name'])){
295             if($this->checkName()){
296                 $roo->jok('OK');
297             }
298             
299             $roo->jerr('EXIST');
300         }
301         
302         if(!empty($this->is_system) && 
303             ($old->code != $this->code  ) // used to be not allowed to change name..
304         ){
305             $roo->jerr('This company is not allow to editing Ref. or Company Name...');
306         }
307     }
308     
309     function beforeDelete($req, $roo)
310     {
311         
312         // should check for members....
313         if(!empty($this->is_system) && 
314             ($old->code != $this->code || $old->name != $this->name)
315         ){
316             $roo->jerr('This company is not allow to delete');
317         }
318         
319         
320     }
321     function onDelete($req, $roo)
322     {   
323         $img = DB_DataObject::factory('Images');
324         $img->ontable = $this->tableName();
325         $img->onid = $this->id;
326         $img->find();
327         while ($img->fetch()) {
328             $img->beforeDelete();
329             $img->delete();
330         }
331         return true;
332         
333          
334     }
335     /**
336      * check who is trying to access this. false == access denied..
337      */
338     function checkPerm($lvl, $au, $changes = false) 
339     {
340         
341         // do we have an empty system..
342         if ($au && $au->id == -1) {
343             return true;
344         }
345         
346         
347         
348         if ($au->company()->comptype != 'OWNER') {
349             
350             // hacking!
351             if ($changes && isset($changes['comptype']) && $changes['comptype'] != $this->comptype) {
352                 return false;
353             }
354             
355             return $this->id == $au->company_id;
356         }
357         
358         return $au->hasPerm("Core.Companies", $lvl);    
359     }
360     
361     function logoImageToHTML($size)
362     {
363         $i = DB_DataObject::factory('Images');
364         if (!$this->logo_id || !$i->get($this->logo_id)) {
365             return '';
366         }
367         return $i->toHTML($size);
368         
369     }
370      function firstImage($filter='image/%')
371     {
372         $i = DB_DataObject::factory('Images');
373         //DB_DataObject::debugLevel(1);
374         $im = $i->gather($this, $filter);
375         if (empty($im)) {
376             return false;
377         }
378         return $im[0];
379     }
380     
381     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
382     {
383         $fm = $this->firstImage($filter);
384          if (empty($fm)) {
385             return '';
386         }
387         return $fm->toHTML($size, $base);
388     }
389     
390     function toRooSingleArray($authUser, $request)
391     {
392         $ret = $this->toArray();
393        // DB_DataObject::debugLevel(1);
394         // get the comptype display
395         $e = DB_DataObject::Factory('core_enum')->lookupObject('COMPTYPE', $this->comptype);
396         
397         $ret['comptype_display'] = $ret['comptype'];
398         if ($e   && !empty($e->name_display)) {
399             $ret['comptype_display'] = $e->name_display;
400         }
401         
402         
403         return $ret;
404     }
405     
406     /**
407      * # 2028 
408      * create the suppliers...
409      * 
410      * @param object $roo
411      * @param array $data
412      * 
413      */
414     function initCompaniesArray($roo, $data)
415     {
416         $tn = $this->tableName();
417         
418         foreach($data as $d){
419             $com = DB_DataObject::factory($tn);
420             $com->setFrom($d);
421             if(!$com->find(true)){
422                 $com->created_dt = Date('Y-m-d H:i:s');
423                 $com->updated_dt = Date('Y-m-d H:i:s');
424                 $com->is_system = 1;// new column.. block the user changing the code and name..
425                 $com->insert();
426             }
427         }
428         
429         
430     }
431     
432     
433     function initCompanies($roo, $opts)
434     {
435         $companies = DB_DataObject::factory('core_company');
436         
437         $ctype = empty($opts['add-company-with-type']) ? 'OWNER' : $opts['add-company-with-type'];
438         
439         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
440         
441         if (empty($enum)) {
442             $roo->jerr("invalid company type '$ctype'");
443         }
444         if ($ctype =='OWNER') {
445             $companies = DB_DataObject::factory('core_company');
446             $companies->comptype_id = $enum;
447             if ($companies->count()) {
448                 $roo->jerr("Owner  company already exists");
449             }
450         }
451         $companies = DB_DataObject::factory('core_company');
452         
453         // check that 
454         $companies->setFrom(array(
455             'name' => $opts['add-company'],
456             'comptype' => $ctype,
457             'comptype_id' => $enum,
458         ));
459         if ($companies->find(true)) {
460             $roo->jerr("company already exists");
461         }
462         $companies->setFrom(array(
463             'background_color' => '',
464             'created_dt' => $this->sqlValue('NOW()'),
465             'updated_dt' => $this->sqlValue('NOW()')
466         ));
467         
468         
469         $companies->insert();
470         $companies->onInsert(array(), $roo);
471     }
472     static function lookupOwner()
473     {
474         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', 'OWNER'  );
475         $companies = DB_DataObject::factory('core_company');
476         $companies->comptype_id = $enum;
477         if ($companies->find(true)) {
478             return $companies;
479         }
480         return false;
481     }
482     
483     function merge($merge_to, $roo)
484     {
485         $affects  = array();
486         
487         $all_links = $this->databaseLinks();
488         
489         foreach($all_links as $tbl => $links) {
490             foreach($links as $col => $totbl_col) {
491                 $to = explode(':', $totbl_col);
492                 if ($to[0] != $this->tableName()) {
493                     continue;
494                 }
495                 
496                 $affects[$tbl .'.' . $col] = true;
497             }
498         }
499         
500         foreach($affects as $k => $true) {
501             $ka = explode('.', $k);
502
503             $chk = DB_DataObject::factory($ka[0]);
504             
505             if (!is_a($chk,'DB_DataObject')) {
506                 $roo->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
507             }
508             
509             $chk->{$ka[1]} = $this->id;
510
511             foreach ($chk->fetchAll() as $c){
512                 $cc = clone ($c);
513                 $c->{$ka[1]} = $merge_to;
514                 $c->update($cc);
515             }
516         }
517         
518         $this->delete();
519         
520         $roo->jok('Merged');
521         
522     }
523     
524     function checkName()
525     {
526         $company = DB_DataObject::factory('core_company');
527         $company->setFrom(array(
528             'name' => $this->name
529         ));
530         
531         if(!empty($this->id)){
532             $company->whereAdd("id != {$this->id}");
533         }
534         
535         if(!$company->find(true)){
536             return true;
537         }
538         
539         return false;
540     }
541 }