3 * Table Definition for Images
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Images extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Images'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $filename; // string(255) not_null
15 public $ontable; // string(32) not_null multiple_key
16 public $onid; // int(11) not_null
17 public $mimetype; // string(64) not_null
18 public $width; // int(11) not_null
19 public $height; // int(11) not_null
20 public $filesize; // int(11) not_null
21 public $displayorder; // int(11) not_null
22 public $language; // string(6) not_null
23 public $parent_image_id; // int(11) not_null
24 public $created; // datetime(19) not_null binary
25 public $imgtype; // string(32) not_null
26 public $linkurl; // string(254) not_null
27 public $descript; // blob(65535) not_null blob
28 public $title; // string(128) not_null
30 /* the code above is auto generated do not remove the tag below */
32 function applyFilters($q, $au, $roo)
34 $tn = $this->tableName();
36 if(!empty($q['search']['filename'])){
38 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%'
40 echo "$tn.filename LIKE '%{$this->escape($q['search']['filename'])}%'"; die;
46 function checkPerm($lvl, $au)
48 // default permissons are to
49 // allow create / edit / if the user has
57 if (method_exists($o, 'checkPerm')) {
58 // edit permissions on related object needed...
59 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
63 return true; //// ??? not really that safe...
67 function beforeInsert($q, $roo)
69 if (isset($q['_remote_upload'])) {
70 require_once 'System.php';
72 $tmpdir = System::mktemp("-d remote_upload");
74 $path = $tmpdir . '/' . basename($q['_remote_upload']);
76 if(!file_exists($path)){
77 file_put_contents($path, file_get_contents($q['_remote_upload']));
80 $imageInfo = getimagesize($path);
82 require_once 'File/MimeType.php';
83 $y = new File_MimeType();
84 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
86 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
87 rename($path,$path.".".$ext);
91 if (!$this->createFrom($path)) {
92 $roo->jerr("erro making image" . $q['_remote_upload']);
95 if(!empty($q['_return_after_create'])){
99 $roo->addEvent("ADD", $this, $this->toEventString());
101 $r = DB_DataObject::factory($this->tableName());
106 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
113 * create an email from file.
114 * these must have been set first.
118 function createFrom($file, $filename=false)
120 // copy the file into the storage area..
121 if (!file_exists($file) || !filesize($file)) {
122 $this->err = "File $file did not exist or is 0 size";
126 $filename = empty($filename) ? $file : $filename;
128 if (empty($this->mimetype)) {
129 require_once 'File/MimeType.php';
130 $y = new File_MimeType();
131 $this->mimetype = $y->fromFilename($filename);
134 $this->mimetype = strtolower($this->mimetype);
136 $mta = explode('/', $this->mimetype);
137 if (array_shift($mta) == 'image') {
139 $imgs = @getimagesize($file);
141 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
144 list($this->width , $this->height) = $imgs;
148 if($this->mimetype == 'application/pdf'){
149 $this->no_of_pages = $this->getPdfPages($file);
152 $this->filesize = filesize($file);
153 $this->created = date('Y-m-d H:i:s');
156 if (empty($this->filename)) {
157 $this->filename = basename($filename);
160 //DB_DataObject::debugLevel(1);
169 $f = $this->getStoreName();
171 if (!file_exists($dest)) {
172 // currently this is 0775 due to problems using shared hosing (FTP)
173 // it makes all the files unaccessable..
174 // you can normally solve this by giving the storedirectory better perms
175 // if needed on a dedicated server..
176 $oldumask = umask(0);
177 mkdir($dest, 0775, true);
188 // $this->createThumbnail(0,50);
194 * Calculate target file name
196 * @return - target file name
198 function getStoreName()
200 $opts = HTML_FlexyFramework::get()->Pman;
201 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
202 return implode( '/', array(
203 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
209 * deletes all the image instances of it...
213 function beforeDelete($dependants_array, $roo)
216 $opts = HTML_FlexyFramework::get()->Pman;
217 $deldir = $opts['storedir']. '/_deleted_images_';
218 if (!file_exists( $deldir )) {
219 mkdir($deldir, 0755);
222 $fn = $this->getStoreName();
224 if (file_exists($fn)) {
226 if (file_exists($deldir . '/'. $b)) {
229 rename($fn, $deldir .'/'. $b);
237 if (file_exists($d)) {
240 while (false !== ($fn = readdir($dh))) {
241 if (substr($fn, 0, strlen($b)) == $b) {
243 if (file_exists($deldir . '/'. $fn)) {
244 unlink($d. '/'. $fn);
247 rename($d. '/'. $fn, $deldir .'/'. $fn);
255 * check mimetype against type
256 * - eg. img.is(#image#)
261 if (empty($this->mimetype)) {
264 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
268 * onUpload (singlely attached image to a table)
271 function onUploadWithTbl($tbl, $fld)
273 if ( $tbl->__table == 'Images') {
274 return; // not upload to self...
276 if (empty($_FILES['imageUpload']['tmp_name']) ||
277 empty($_FILES['imageUpload']['name']) ||
278 empty($_FILES['imageUpload']['type'])
283 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
285 $image = DB_DataObject::factory('Images');
286 $image->get($tbl->$fld);
287 $image->beforeDelete();
291 $image = DB_DataObject::factory('Images');
292 $image->onid = $tbl->id;
293 $image->ontable = $tbl->__table;
294 $image->filename = $_FILES['imageUpload']['name'];
295 $image->mimetype = $_FILES['imageUpload']['type'];
297 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
301 $tbl->$fld = $image->id;
308 function onUpload($roo)
310 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
311 if (empty($_FILES['imageUpload']['tmp_name']) ||
312 empty($_FILES['imageUpload']['name']) ||
313 empty($_FILES['imageUpload']['type'])
317 0=>"There is no error, the file uploaded with success",
318 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
319 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
320 3=>"The uploaded file was only partially uploaded",
321 4=>"No file was uploaded",
322 6=>"Missing a temporary folder"
324 $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
325 $this->err = "Missing file details : Error=". $estr;
330 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
332 $this->beforeDelete();
334 if ( empty($this->ontable)) {
335 $this->err = "Missing ontable";
339 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
340 // then its an upload
341 $img = DB_DataObject::factory('Images');
342 $img->onid = $this->onid;
343 $img->ontable = $this->ontable;
344 $img->imgtype = $this->imgtype;
347 while ($img->fetch()) {
348 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
350 $img->beforeDelete();
358 require_once 'File/MimeType.php';
359 $y = new File_MimeType();
360 $this->mimetype = $_FILES['imageUpload']['type'];
361 if (in_array($this->mimetype, array(
363 'application/octet-stream',
364 'image/x-png', // WTF does this?
365 'image/pjpeg', // WTF does this?
366 'application/x-apple-msg-attachment', /// apple doing it's magic...
367 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
368 'application/csv-tab-delimited-table', // windows again!!?
369 ))) { // weird tyeps..
370 $inf = pathinfo($_FILES['imageUpload']['name']);
371 $this->mimetype = $y->fromExt($inf['extension']);
375 $ext = $y->toExt(trim((string) $this->mimetype ));
377 $this->filename = empty($this->filename) ?
378 $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext);
382 if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
383 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
393 * return a list of images for an object, optionally with a mime regex.
394 * eg. '%/pdf' or 'image/%'
398 * $i = DB_DataObject::factory('Images');
399 * $i->imgtype = 'LOGO';
400 * $ar = $i->gather($somedataobject, 'image/%');
402 * @param {DB_DataObject} dataobject = the object to gather data on.
403 * @param {String} mimelike LIKE query to use for search
406 function gather($obj, $mime_like='', $opts=array())
408 //DB_DataObject::debugLevel(1);
409 if (empty($obj->id)) {
414 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
417 if (!empty($mime_like)) {
418 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
420 $c->orderBy('created DESC');
422 return $c->fetchAll();
427 * set or get the dataobject this image is associated with
428 * @param DB_DataObject $obj An object to associate this image with
429 * (does not store it - you need to call update() to do that)
430 * @return DB_DataObject the dataobject this image is attached to.
432 function object($obj=false)
434 if ($obj === false) {
435 if (empty($this->ontable) || empty($this->onid)) {
438 $ret = DB_DataObject::factory($this->ontable);
439 $ret->get($this->onid);
444 $this->ontable = $obj->tableName();
445 $this->onid = $obj->id; /// assumes our nice standard of using ids..
450 function toRooArray($req) {
452 $ret= $this->toArray();
456 $ff = HTML_FlexyFramework::get();
459 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
460 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
462 if (!empty($req['query']['imagesize'])) {
463 // query/imageBaseURL ... depricated...? -- set it in config?
465 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
467 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
469 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
471 if (!empty($req['query']['imagesize'])) {
472 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
482 * URL - create a url for the image.
483 * size - use -1 to show full size.
484 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
488 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
491 return 'about:blank';
495 $ff = HTML_FlexyFramework::get();
496 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
497 if (preg_match('#^http[s]*://#', $provider)) {
502 $provider = preg_replace('#/Thumb$#', '', $provider);
504 return $baseURL . $provider . "/{$this->id}/{$this->filename}";
507 //$size = max(100, (int) $size);
508 //$size = min(1024, (int) $size);
509 // the size should 200x150 to convert
510 $sizear = preg_split('/(x|c)/', $size);
511 if(empty($sizear[1])){
514 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
516 $fc = $this->toFileConvert();
519 $mt = $this->mimetype;
520 if (!preg_match('#^image/#i',$mt)) {
524 $fc->convert($mt, $size);
526 return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
529 * size could be 123x345
533 function toHTML($size, $provider = '/Images/Thumb')
538 $sz = explode('x', $size);
541 if (!$this->id || empty($this->width)) {
543 $this->width = empty($sz[1]) ? $sx : $sz[1];
547 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
554 if (strlen($this->title)) {
555 $extra = ' title="'. htmlspecialchars($this->title) . '"';
558 return '<img src="' . $this->URL($size, $provider) . '"' .
560 ' width="'. $sx . '"' .
561 ' height="'. $sy . '">';
568 * #2142 [new] CMS - image link urls
573 function toLinkHTML($size, $provider = '/Images/Thumb')
575 if(empty($this->linkurl)){
576 return $this->toHTML($size, $provider = '/Images/Thumb');
579 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
585 * to Fileconvert object..
590 function toFileConvert()
592 require_once 'File/Convert.php';
593 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
600 require_once 'File/MimeType.php';
602 $y = new File_MimeType();
603 return $y->toExt($this->mimetype);
615 function setFromRoo($ar, $roo)
617 // not sure why we do this..
619 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
620 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
623 if ($this->find(true)) {
624 $roo->old = clone($this);
629 if (!empty($ar['_copy_from'])) {
631 if (!$this->checkPerm( 'A' , $roo->authUser)) {
632 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
635 $copy = DB_DataObject::factory('Images');
636 $copy->get($ar['_copy_from']);
637 $this->setFrom($copy->toArray());
639 $this->createFrom($copy->getStoreName());
641 $roo->addEvent("ADD", $this, $this->toEventString());
643 $r = DB_DataObject::factory($this->tableName());
648 $roo->jok($r->toArray());
655 // FIXME - we should be checking perms here...
657 // this should be doign update
660 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
661 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
666 if (!isset($_FILES['imageUpload'])) {
667 return; // standard update...
671 // print_r(!$this->onUpload($this));
673 if ( !$this->onUpload($this)) {
674 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
677 $this->addEvent($ar, $roo);
679 $r = DB_DataObject::factory($this->tableName());
684 $roo->jok($r->toArray());
688 function addEvent($ar, $roo)
690 $roo->addEvent("ADD", $this, $this->toEventString());
693 function toEventString()
696 //$p = DB_DataObject::factory($this->ontable);
698 // return "ERROR unknown table? {$this->ontable}";
702 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
703 //$p->toEventString();
706 function onUploadFromData($data, $roo)
709 $this->err = "Missing file details";
714 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
716 $this->beforeDelete();
719 if (empty($this->ontable)) {
720 $this->err = "Missing ontable";
724 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
725 // then its an upload
726 $img = DB_DataObject::factory('Images');
727 $img->onid = $this->onid;
728 $img->ontable = $this->ontable;
729 $img->imgtype = $this->imgtype;
732 while ($img->fetch()) {
733 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
735 $img->beforeDelete();
741 require_once 'File/MimeType.php';
742 $y = new File_MimeType();
744 if (in_array($this->mimetype, array(
746 'application/octet-stream',
747 'image/x-png', // WTF does this?
748 'image/pjpeg', // WTF does this?
749 'application/x-apple-msg-attachment', /// apple doing it's magic...
750 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
751 'application/csv-tab-delimited-table', // windows again!!?
752 ))) { // weird tyeps..
753 $inf = pathinfo($this->filename);
754 $this->mimetype = $y->fromExt($inf['extension']);
757 $ext = $y->toExt(trim((string) $this->mimetype ));
759 if(array_pop(explode('.', $this->filename)) != $ext){
760 $this->filename = $this->filename .'.'. $ext;
763 if (!$this->createFromData($data)) {
771 function createFromData($data)
774 $this->mimetype= strtolower($this->mimetype);
776 if (array_shift(explode('/', $this->mimetype)) == 'image') {
778 $imgs = @getimagesize($data);
780 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
781 list($this->width , $this->height) = $imgs;
785 $this->created = date('Y-m-d H:i:s');
793 $f = $this->getStoreName();
795 if (!file_exists($dest)) {
796 $oldumask = umask(0);
797 mkdir($dest, 0775, true);
801 file_put_contents($f, file_get_contents("data://" . $data));
805 $this->filesize = filesize($f);
807 if($this->mimetype == 'application/pdf'){
808 $this->no_of_pages = $this->getPdfPages($f);
819 if(!preg_match('/^image\//', $this->mimetype)){
823 $file = $this->getStoreName();
825 if(!file_exists($file)){
829 $data = file_get_contents($file);
831 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
836 function getPdfPages($file)
838 require_once 'System.php';
842 $pdfinfo = System::which('pdfinfo');
844 if (!file_exists($file) || empty($pdfinfo)) {
848 $cmd = "{$pdfinfo} {$file}";
852 $info = explode("\n", $ret);
854 foreach ($info as $i){
856 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
860 $page = (empty($matches[1])) ? 0 : $matches[1];