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'])}%' OR $tn.title LIKE '%{$this->escape($q['search']['filename'])}%'
45 function checkPerm($lvl, $au)
47 // default permissons are to
48 // allow create / edit / if the user has
56 if (method_exists($o, 'checkPerm')) {
57 // edit permissions on related object needed...
58 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
62 return true; //// ??? not really that safe...
66 function beforeInsert($q, $roo)
68 if (isset($q['_remote_upload'])) {
69 require_once 'System.php';
71 $tmpdir = System::mktemp("-d remote_upload");
73 $path = $tmpdir . '/' . basename($q['_remote_upload']);
75 if(!file_exists($path)){
76 file_put_contents($path, file_get_contents($q['_remote_upload']));
79 $imageInfo = getimagesize($path);
81 require_once 'File/MimeType.php';
82 $y = new File_MimeType();
83 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
85 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
86 rename($path,$path.".".$ext);
90 if (!$this->createFrom($path)) {
91 $roo->jerr("erro making image" . $q['_remote_upload']);
94 if(!empty($q['_return_after_create'])){
98 $roo->addEvent("ADD", $this, $this->toEventString());
100 $r = DB_DataObject::factory($this->tableName());
105 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
112 * create an email from file.
113 * these must have been set first.
117 function createFrom($file, $filename=false)
119 // copy the file into the storage area..
120 if (!file_exists($file) || !filesize($file)) {
121 $this->err = "File $file did not exist or is 0 size";
125 $filename = empty($filename) ? $file : $filename;
127 if (empty($this->mimetype)) {
128 require_once 'File/MimeType.php';
129 $y = new File_MimeType();
130 $this->mimetype = $y->fromFilename($filename);
133 $this->mimetype = strtolower($this->mimetype);
135 $mta = explode('/', $this->mimetype);
136 if (array_shift($mta) == 'image') {
138 $imgs = @getimagesize($file);
140 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
143 list($this->width , $this->height) = $imgs;
147 if($this->mimetype == 'application/pdf'){
148 $this->no_of_pages = $this->getPdfPages($file);
151 $this->filesize = filesize($file);
152 $this->created = date('Y-m-d H:i:s');
155 if (empty($this->filename)) {
156 $this->filename = basename($filename);
159 //DB_DataObject::debugLevel(1);
168 $f = $this->getStoreName();
170 if (!file_exists($dest)) {
171 // currently this is 0775 due to problems using shared hosing (FTP)
172 // it makes all the files unaccessable..
173 // you can normally solve this by giving the storedirectory better perms
174 // if needed on a dedicated server..
175 $oldumask = umask(0);
176 mkdir($dest, 0775, true);
187 // $this->createThumbnail(0,50);
193 * Calculate target file name
195 * @return - target file name
197 function getStoreName()
199 $opts = HTML_FlexyFramework::get()->Pman;
200 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
201 return implode( '/', array(
202 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
208 * does the files exist?
212 return file_exists($this->getStoreName());
217 * deletes all the image instances of it...
221 function beforeDelete($dependants_array, $roo)
224 if (!empty($dependants_array)) {
228 $opts = HTML_FlexyFramework::get()->Pman;
229 $deldir = $opts['storedir']. '/_deleted_images_';
230 if (!file_exists( $deldir )) {
231 mkdir($deldir, 0755);
234 $fn = $this->getStoreName();
236 if (file_exists($fn)) {
238 if (file_exists($deldir . '/'. $b)) {
241 rename($fn, $deldir .'/'. $b);
249 if (file_exists($d)) {
252 while (false !== ($fn = readdir($dh))) {
253 if (substr($fn, 0, strlen($b)) == $b) {
255 if (file_exists($deldir . '/'. $fn)) {
256 unlink($d. '/'. $fn);
259 rename($d. '/'. $fn, $deldir .'/'. $fn);
267 * check mimetype against type
268 * - eg. img.is(#image#)
273 if (empty($this->mimetype)) {
276 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
280 * onUpload (singlely attached image to a table)
283 function onUploadWithTbl($tbl, $fld)
285 if ( $tbl->__table == 'Images') {
286 return; // not upload to self...
288 if (empty($_FILES['imageUpload']['tmp_name']) ||
289 empty($_FILES['imageUpload']['name']) ||
290 empty($_FILES['imageUpload']['type'])
295 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
297 $image = DB_DataObject::factory('Images');
298 $image->get($tbl->$fld);
299 $image->beforeDelete();
303 $image = DB_DataObject::factory('Images');
304 $image->onid = $tbl->id;
305 $image->ontable = $tbl->__table;
306 $image->filename = $_FILES['imageUpload']['name'];
307 $image->mimetype = $_FILES['imageUpload']['type'];
309 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
313 $tbl->$fld = $image->id;
320 function onUpload($roo, $table = false, $file = false)
323 if ($table !== false) {
324 $this->ontable = $table->tableName();
325 $this->onid = $table->pid();
328 if ($file === false) {
329 $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
332 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
333 if (empty($file['tmp_name']) ||
334 empty($file['name']) ||
339 0=>"There is no error, the file uploaded with success",
340 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
341 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
342 3=>"The uploaded file was only partially uploaded",
343 4=>"No file was uploaded",
344 6=>"Missing a temporary folder"
346 $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
347 $this->err = "Missing file details : Error=". $estr;
352 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
354 $this->beforeDelete();
356 if ( empty($this->ontable)) {
357 $this->err = "Missing ontable";
361 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
362 // then its an upload
363 $img = DB_DataObject::factory('Images');
364 $img->onid = $this->onid;
365 $img->ontable = $this->ontable;
366 $img->imgtype = $this->imgtype;
369 while ($img->fetch()) {
370 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
372 $img->beforeDelete();
380 require_once 'File/MimeType.php';
381 $y = new File_MimeType();
382 $this->mimetype = $file['type'];
383 if (in_array($this->mimetype, array(
385 'application/octet-stream',
386 'image/x-png', // WTF does this?
387 'image/pjpeg', // WTF does this?
388 'application/x-apple-msg-attachment', /// apple doing it's magic...
389 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
390 'application/csv-tab-delimited-table', // windows again!!?
391 ))) { // weird tyeps..
392 $inf = pathinfo($file['name']);
393 $this->mimetype = $y->fromExt($inf['extension']);
397 $ext = $y->toExt(trim((string) $this->mimetype ));
399 $this->filename = empty($this->filename) ?
400 $file['name'] : ($this->filename .'.'. $ext);
404 if (!$this->createFrom($file['tmp_name'])) {
405 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
415 * return a list of images for an object, optionally with a mime regex.
416 * eg. '%/pdf' or 'image/%'
420 * $i = DB_DataObject::factory('Images');
421 * $i->imgtype = 'LOGO';
422 * $ar = $i->gather($somedataobject, 'image/%');
424 * @param {DB_DataObject} dataobject = the object to gather data on.
425 * @param {String} mimelike LIKE query to use for search
428 function gather($obj, $mime_like='', $opts=array())
430 //DB_DataObject::debugLevel(1);
431 if (empty($obj->id)) {
436 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
439 if (!empty($mime_like)) {
440 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
442 $c->orderBy('created DESC');
444 return $c->fetchAll();
449 * set or get the dataobject this image is associated with
450 * @param DB_DataObject $obj An object to associate this image with
451 * (does not store it - you need to call update() to do that)
452 * @return DB_DataObject the dataobject this image is attached to.
454 function object($obj=false)
456 if ($obj === false) {
457 if (empty($this->ontable) || empty($this->onid)) {
460 $ret = DB_DataObject::factory($this->ontable);
461 $ret->get($this->onid);
466 $this->ontable = $obj->tableName();
467 $this->onid = $obj->id; /// assumes our nice standard of using ids..
472 function toRooArray($req)
475 $ret= $this->toArray();
478 $ff = HTML_FlexyFramework::get();
481 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
482 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
484 if (!empty($req['query']['imagesize'])) {
485 // query/imageBaseURL ... depricated...? -- set it in config?
487 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
489 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
491 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
493 if (!empty($req['query']['imagesize'])) {
494 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
499 $ret['shorten_name'] = $ret['filename'] = $this->shorten_name();
505 * URL - create a url for the image.
506 * size - use -1 to show full size.
507 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
511 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
514 return 'about:blank';
516 if (!$this->exists()) {
517 return 'about:missing';
520 $shorten_name = $this->shorten_name();
522 $ff = HTML_FlexyFramework::get();
523 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
524 if (preg_match('#^http[s]*://#', $provider)) {
529 $provider = preg_replace('#/Thumb$#', '', $provider);
531 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
534 //$size = max(100, (int) $size);
535 //$size = min(1024, (int) $size);
536 // the size should 200x150 to convert
537 $sizear = preg_split('/(x|c)/', $size);
538 if(empty($sizear[1])){
541 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
543 $fc = $this->toFileConvert();
546 $mt = $this->mimetype;
547 if (!preg_match('#^image/#i',$mt)) {
551 $fc->convert($mt, $size);
553 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
556 function getFromHashURL($url)
559 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
561 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
563 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
567 if ($id === false || $id < 1) {
571 $img = DB_DAtaObject::Factory('images');
572 if ($img->get($id)) {
579 function shorten_name()
581 if(empty($this->filename)) {
585 $filename = explode('.', $this->filename);
586 $ext = array_pop($filename);
587 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
589 if(strlen($name) > 32) {
590 $name = substr($name, 0, 32);
593 $shorten_name = "{$name}.{$ext}";
595 return $shorten_name;
598 * size could be 123x345
602 function toHTML($size, $provider = '/Images/Thumb')
607 $sz = explode('x', $size);
610 if (!$this->id || empty($this->width)) {
612 $this->width = empty($sz[1]) ? $sx : $sz[1];
616 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
623 if (strlen($this->title)) {
624 $extra = ' title="'. htmlspecialchars($this->title) . '"';
627 return '<img src="' . $this->URL($size, $provider) . '"' .
629 ' width="'. $sx . '"' .
630 ' height="'. $sy . '">';
637 * #2142 [new] CMS - image link urls
642 function toLinkHTML($size, $provider = '/Images/Thumb')
644 if(empty($this->linkurl)){
645 return $this->toHTML($size, $provider = '/Images/Thumb');
648 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
654 * to Fileconvert object..
659 function toFileConvert()
661 require_once 'File/Convert.php';
662 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
669 require_once 'File/MimeType.php';
671 $y = new File_MimeType();
672 return $y->toExt($this->mimetype);
684 function setFromRoo($ar, $roo)
686 // not sure why we do this..
688 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
689 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
692 if ($this->find(true)) {
693 $roo->old = clone($this);
698 if (!empty($ar['_copy_from'])) {
700 if (!$this->checkPerm( 'A' , $roo->authUser)) {
701 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
704 $copy = DB_DataObject::factory('Images');
705 $copy->get($ar['_copy_from']);
706 $this->setFrom($copy->toArray());
708 $this->createFrom($copy->getStoreName());
710 $roo->addEvent("ADD", $this, $this->toEventString());
712 $r = DB_DataObject::factory($this->tableName());
718 $roo->jok($r->toRooArray($ar));
725 // FIXME - we should be checking perms here...
727 // this should be doign update
730 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
731 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
735 if (!isset($_FILES['imageUpload'])) {
736 return; // standard update...
740 // print_r(!$this->onUpload($this));
742 if ( !$this->onUpload($this)) {
743 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
746 $this->addEvent($ar, $roo);
748 $r = DB_DataObject::factory($this->tableName());
753 $roo->jok($r->toRooArray($ar));
757 function addEvent($ar, $roo)
759 $roo->addEvent("ADD", $this, $this->toEventString());
762 function toEventString()
765 //$p = DB_DataObject::factory($this->ontable);
767 // return "ERROR unknown table? {$this->ontable}";
771 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
772 //$p->toEventString();
775 function onUploadFromData($data, $roo)
778 $this->err = "Missing file details";
783 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
785 $this->beforeDelete();
788 if (empty($this->ontable)) {
789 $this->err = "Missing ontable";
793 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
794 // then its an upload
795 $img = DB_DataObject::factory('Images');
796 $img->onid = $this->onid;
797 $img->ontable = $this->ontable;
798 $img->imgtype = $this->imgtype;
801 while ($img->fetch()) {
802 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
804 $img->beforeDelete();
810 require_once 'File/MimeType.php';
811 $y = new File_MimeType();
813 if (in_array($this->mimetype, array(
815 'application/octet-stream',
816 'image/x-png', // WTF does this?
817 'image/pjpeg', // WTF does this?
818 'application/x-apple-msg-attachment', /// apple doing it's magic...
819 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
820 'application/csv-tab-delimited-table', // windows again!!?
821 ))) { // weird tyeps..
822 $inf = pathinfo($this->filename);
823 $this->mimetype = $y->fromExt($inf['extension']);
826 $ext = $y->toExt(trim((string) $this->mimetype ));
828 $explode_filename = explode('.', $this->filename);
829 if(array_pop($explode_filename) != $ext){
830 $this->filename = $this->filename .'.'. $ext;
833 if (!$this->createFromData($data)) {
841 function createFromData($data)
844 if (0 === strpos($data, "data:")) {
845 // data:image/png;base64,
846 $data = substr($data,5);
847 $bits = explode(";", $data);
848 $this->mimetype = $bits[0];
851 if (empty($this->filename)) {
852 require_once 'File/MimeType.php';
853 $y = new File_MimeType();
854 $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
858 $this->mimetype = strtolower($this->mimetype);
860 $explode_mimetype = explode('/', $this->mimetype);
862 if (array_shift($explode_mimetype) == 'image') {
864 $imgs = @getimagesize('data://'. $data);
866 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
867 list($this->width , $this->height) = $imgs;
871 $this->created = date('Y-m-d H:i:s');
879 $f = $this->getStoreName();
881 if (!file_exists($dest)) {
882 $oldumask = umask(0);
883 mkdir($dest, 0775, true);
887 file_put_contents($f, file_get_contents("data://" . $data));
891 $this->filesize = filesize($f);
893 if($this->mimetype == 'application/pdf'){
894 $this->no_of_pages = $this->getPdfPages($f);
903 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
905 if(!preg_match('/^image\//', $this->mimetype)){
909 $file = $this->getStoreName();
911 if(!file_exists($file)){
915 $data = file_get_contents($file);
917 if(!empty($scaleWidth) || !empty($scaleHeight)){
918 $data = $this->scale(false, $scaleWidth, $scaleHeight);
922 $data = $this->rotate($data);
925 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
930 function getPdfPages($file)
932 require_once 'System.php';
936 $pdfinfo = System::which('pdfinfo');
938 if (!file_exists($file) || empty($pdfinfo)) {
942 $cmd = "{$pdfinfo} {$file}";
946 $info = explode("\n", $ret);
948 foreach ($info as $i){
950 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
954 $page = (empty($matches[1])) ? 0 : $matches[1];
960 function rotate($imageBlob = false)
962 if(empty($imageBlob)){
963 $imagick = new Imagick($this->getStoreName());
965 $imagick = new Imagick();
966 $imagick->readImageBlob($imageBlob);
969 $orientation = $imagick->getImageOrientation();
971 switch($orientation) {
972 case Imagick::ORIENTATION_BOTTOMRIGHT:
973 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
976 case Imagick::ORIENTATION_RIGHTTOP:
977 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
980 case Imagick::ORIENTATION_LEFTBOTTOM:
981 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
985 return $imagick->getImageBlob();
988 function scale($imageBlob = false, $width = 0, $height = 0)
990 if(empty($imageBlob)){
991 $imagick = new Imagick($this->getStoreName());
993 $imagick = new Imagick();
994 $imagick->readImageBlob($imageBlob);
997 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
999 return $imagick->getImageBlob();