Fix #5702 - Supplier contact details - extra fields
[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)  blobeforeDeleteb
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']) || !empty($q['search']['name'])){
108             
109             $s = (!empty($q['query']['name'])) ? $this->escape($q['query']['name']) : $this->escape($q['search']['name']);
110             
111             $this->whereAdd("
112                 {$tn}.name LIKE '%$s%'
113             ");
114         }
115         
116         if(!empty($q['query']['name_starts']) || !empty($q['search']['name_starts'])){
117             
118             $s = (!empty($q['query']['name_starts'])) ? $this->escape($q['query']['name_starts']) : $this->escape($q['search']['name_starts']);
119             
120             $this->whereAdd("
121                 {$tn}.name LIKE '$s%'
122             ");
123         }
124     }
125     
126     function toEventString() {
127         return $this->name;
128     }
129     
130     // ---------- AUTHENTICATION
131     // not sure where authetnication via company is used?? posibly media-outreach
132     
133     function isAuth()
134     {
135         $db = $this->getDatabaseConnection();
136         $sesPrefix = $db->dsn['database'];
137         @session_start();
138         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
139             // in session...
140             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
141             $u = DB_DataObject::factory('core_company');
142             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
143                 return true;
144             }
145             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
146             
147         }
148         // not in session or not matched...
149         
150         
151         return false;
152         
153     }
154     function getAuthUser()
155     {
156         if (!$this->isAuth()) {
157             return false;
158         }
159         $db = $this->getDatabaseConnection();
160         $sesPrefix = $db->dsn['database'];
161         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
162             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
163             
164             $u = DB_DataObject::factory('core_company');
165             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
166                 return clone($u);
167             }
168              
169         }
170         
171         
172         return false;
173     }     
174     function login()
175     {
176         $this->isAuth(); // force session start..
177          $db = $this->getDatabaseConnection();
178         $sesPrefix = $db->dsn['database'];
179         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
180         
181     }
182     function logout()
183     {
184         $this->isAuth(); // force session start..
185         $db = $this->getDatabaseConnection();
186         $sesPrefix = $db->dsn['database'];
187         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
188         
189     }    
190     // ---------- AUTHENTICATION
191     function checkPassword($val)
192     {
193         //echo '<pre>'.$val .  print_R($this,true);
194         if (substr($this->passwd,0,1) == '$') {
195             return crypt($val,$this->passwd) == $this->passwd ;
196         }
197         // old style md5 passwords...- cant be used with courier....
198         return md5($val) == $this->passwd;
199     }
200     function setPassword($value) 
201     {
202         $salt='';
203         while(strlen($salt)<9) {
204             $salt.=chr(rand(64,126));
205             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
206         }
207         $this->passwd = crypt($value, '$1$'. $salt. '$');
208        
209     }      
210     function onUpload($controller)
211     {
212         $image = DB_DataObject::factory('Images');
213         return $image->onUploadWithTbl($this, 'logo_id');
214          
215     }
216     function  onUpdate($old, $req,$roo) 
217     {
218         if (!empty($req['password1'])) {
219             $this->setPassword($req['password1']);
220             $this->update();
221         }
222     }
223     function onInsert($req, $roo)
224     {
225         if (!empty($this->logo_id)) { // update images table to sycn with this..
226             $img = DB_DataObject::factory('Images');
227             if ($img->get($this->logo_id) && ($img->onid != $this->id)) {
228                 $img->onid = $this->id;
229                 $img->update();
230             }
231         }
232         if (!empty($req['password1'])) {
233             $this->setPassword($req['password1']);
234             $this->update();
235         }
236         $img = DB_DataObject::factory('Images');
237         $img->onid= 0;
238         
239         $img->ontable = $this->tableName();
240         $img->imgtype = 'LOGO';
241         // should check uploader!!!
242         if ($img->find()) {
243             while($img->fetch()) {
244                 $ii = clone($img);
245                 $ii->onid = $this->id;
246                 $ii->update();
247                 $this->logo_id = $ii->id;
248             }
249             $this->update();
250         }
251         
252     }
253     
254     function beforeInsert($q, $roo)
255     {
256         // we still use comptype in some old systems...
257         
258         if (!empty($q['comptype_id'])) {
259             $en = DB_DataObject::Factory('core_enum');
260             $en->get($q['comptype_id']);
261             $this->comptype = $en->name;
262         }
263         
264         if(!empty($q['_check_name'])){
265             if($this->checkName()){
266                 $roo->jok('OK');
267             }
268             
269             $roo->jerr('EXIST');
270         }
271     }
272     
273     function beforeUpdate($old, $q,$roo)
274     {
275         // we still use comptype in some old systems...
276         
277         if (!empty($q['comptype_id'])) {
278             $en = DB_DataObject::Factory('core_enum');
279             $en->get($q['comptype_id']);
280             $this->comptype = $en->name;
281         }
282         
283         
284         if(!empty($q['_flag_delete'])){
285             $this->deleted_dt = $this->sqlValue("NOW()");
286             $this->deleted_by = $roo->getAuthUser()->id;
287         }
288         
289         if(!empty($q['_flag_undelete'])){
290             $this->deleted_dt = "";
291             $this->deleted_by = 0;
292         }
293         if(!empty($q['_check_name'])){
294             if($this->checkName()){
295                 $roo->jok('OK');
296             }
297             
298             $roo->jerr('EXIST');
299         }
300         
301         if(!empty($q['_merge_id'])){
302             $this->merge($q['_merge_id'], $roo);
303         }
304         
305         if(!empty($this->is_system) && 
306             ($old->code != $this->code  ) // used to be not allowed to change name..
307         ){
308             $roo->jerr('This company is not allow to editing Ref. or Company Name...');
309         }
310     }
311     
312     function beforeDelete($req, $roo)
313     {
314         
315         // should check for members....
316         if(!empty($this->is_system) && 
317             ($old->code != $this->code || $old->name != $this->name)
318         ){
319             $roo->jerr('This company is not allow to delete');
320         }
321         
322         
323     }
324     function onDelete($req, $roo)
325     {   
326         $img = DB_DataObject::factory('Images');
327         $img->ontable = $this->tableName();
328         $img->onid = $this->id;
329         $img->find();
330         while ($img->fetch()) {
331             $img->beforeDelete(array(), $roo);
332             $img->delete();
333         }
334         return true;
335         
336          
337     }
338     /**
339      * check who is trying to access this. false == access denied..
340      */
341     function checkPerm($lvl, $au, $changes = false) 
342     {
343         
344         // do we have an empty system..
345         if ($au && $au->id == -1) {
346             return true;
347         }
348         
349         
350         
351         if ($au->company()->comptype != 'OWNER') {
352             
353             // hacking!
354             if ($changes && isset($changes['comptype']) && $changes['comptype'] != $this->comptype) {
355                 return false;
356             }
357             
358             return $this->id == $au->company_id;
359         }
360         
361         return $au->hasPerm("Core.Companies", $lvl);    
362     }
363     
364     function logoImageToHTML($size)
365     {
366         $i = DB_DataObject::factory('Images');
367         if (!$this->logo_id || !$i->get($this->logo_id)) {
368             return '';
369         }
370         return $i->toHTML($size);
371         
372     }
373      function firstImage($filter='image/%')
374     {
375         $i = DB_DataObject::factory('Images');
376         //DB_DataObject::debugLevel(1);
377         $im = $i->gather($this, $filter);
378         if (empty($im)) {
379             return false;
380         }
381         return $im[0];
382     }
383     
384     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
385     {
386         $fm = $this->firstImage($filter);
387          if (empty($fm)) {
388             return '';
389         }
390         return $fm->toHTML($size, $base);
391     }
392     
393     function toRooSingleArray($authUser, $request)
394     {
395         $ret = $this->toArray();
396        // DB_DataObject::debugLevel(1);
397         // get the comptype display
398         $e = DB_DataObject::Factory('core_enum')->lookupObject('COMPTYPE', $this->comptype);
399         
400         $ret['comptype_display'] = $ret['comptype'];
401         if ($e   && !empty($e->name_display)) {
402             $ret['comptype_display'] = $e->name_display;
403         }
404         
405         
406         return $ret;
407     }
408     
409     /**
410      * # 2028 
411      * create the suppliers...
412      * 
413      * @param object $roo
414      * @param array $data
415      * 
416      */
417     function initCompaniesArray($roo, $data)
418     {
419         $tn = $this->tableName();
420         
421         foreach($data as $d){
422             $com = DB_DataObject::factory($tn);
423             $com->setFrom($d);
424             if(!$com->find(true)){
425                 $com->created_dt = Date('Y-m-d H:i:s');
426                 $com->updated_dt = Date('Y-m-d H:i:s');
427                 $com->is_system = 1;// new column.. block the user changing the code and name..
428                 $com->insert();
429             }
430         }
431         
432         
433     }
434     
435     
436     function initCompanies($roo, $opts)
437     {
438         $companies = DB_DataObject::factory('core_company');
439         
440         $ctype = empty($opts['add-company-with-type']) ? 'OWNER' : $opts['add-company-with-type'];
441         
442         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
443         
444         if (empty($enum)) {
445             $roo->jerr("invalid company type '$ctype'");
446         }
447         if ($ctype =='OWNER') {
448             $companies = DB_DataObject::factory('core_company');
449             $companies->comptype_id = $enum;
450             if ($companies->count()) {
451                 $roo->jerr("Owner  company already exists");
452             }
453         }
454         $companies = DB_DataObject::factory('core_company');
455         
456         // check that 
457         $companies->setFrom(array(
458             'name' => $opts['add-company'],
459             'comptype' => $ctype,
460             'comptype_id' => $enum,
461         ));
462         if ($companies->find(true)) {
463             $roo->jerr("company already exists");
464         }
465         $companies->setFrom(array(
466             'background_color' => '',
467             'created_dt' => $this->sqlValue('NOW()'),
468             'updated_dt' => $this->sqlValue('NOW()')
469         ));
470         
471         
472         $companies->insert();
473         $companies->onInsert(array(), $roo);
474     }
475     static function lookupOwner()
476     {
477         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', 'OWNER'  );
478         $companies = DB_DataObject::factory('core_company');
479         $companies->comptype_id = $enum;
480         if ($companies->find(true)) {
481             return $companies;
482         }
483         return false;
484     }
485     
486     function merge($merge_to, $roo)
487     {
488         $affects  = array();
489         
490         $all_links = $this->databaseLinks();
491         
492         foreach($all_links as $tbl => $links) {
493             foreach($links as $col => $totbl_col) {
494                 $to = explode(':', $totbl_col);
495                 if ($to[0] != $this->tableName()) {
496                     continue;
497                 }
498                 
499                 $affects[$tbl .'.' . $col] = true;
500             }
501         }
502         
503         foreach($affects as $k => $true) {
504             $ka = explode('.', $k);
505
506             $chk = DB_DataObject::factory($ka[0]);
507             
508             if (!is_a($chk,'DB_DataObject')) {
509                 $roo->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
510             }
511             
512             $chk->{$ka[1]} = $this->id;
513
514             foreach ($chk->fetchAll() as $c){
515                 $cc = clone ($c);
516                 $c->{$ka[1]} = $merge_to;
517                 $c->update($cc);
518             }
519         }
520         
521         $this->delete();
522         
523         $roo->jok('Merged');
524         
525     }
526     
527     function checkName()
528     {
529         $company = DB_DataObject::factory('core_company');
530         $company->setFrom(array(
531             'name' => $this->name
532         ));
533         
534         if(!empty($this->id)){
535             $company->whereAdd("id != {$this->id}");
536         }
537         
538         if(!$company->find(true)){
539             return true;
540         }
541         
542         return false;
543     }
544 }