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'])}%'
42 if(!empty($q['_to_base64']) && !empty($q['image_id'])) {
43 $i = DB_DataObject::factory("Images");
44 $i->get($q['image_id']);
45 $roo->jok($i->toBase64());
51 function checkPerm($lvl, $au)
53 // default permissons are to
54 // allow create / edit / if the user has
62 if ($o && method_exists($o, 'checkPerm')) {
63 // edit permissions on related object needed...
64 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
68 return true; //// ??? not really that safe...
72 function beforeInsert($q, $roo)
74 if (isset($q['_remote_upload'])) {
75 require_once 'System.php';
77 $tmpdir = System::mktemp("-d remote_upload");
79 $path = $tmpdir . '/' . basename($q['_remote_upload']);
81 if(!file_exists($path)){
82 file_put_contents($path, file_get_contents($q['_remote_upload']));
85 $imageInfo = getimagesize($path);
87 require_once 'File/MimeType.php';
88 $y = new File_MimeType();
89 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
91 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
92 rename($path,$path.".".$ext);
96 if (!$this->createFrom($path)) {
97 $roo->jerr("erro making image" . $q['_remote_upload']);
100 if(!empty($q['_return_after_create'])){
104 $roo->addEvent("ADD", $this, $this->toEventString());
106 $r = DB_DataObject::factory($this->tableName());
111 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
118 * create an email from file.
119 * these must have been set first.
123 function createFrom($file, $filename=false)
125 // copy the file into the storage area..
126 if (!file_exists($file) || !filesize($file)) {
127 $this->err = "File $file did not exist or is 0 size";
131 $filename = empty($filename) ? $file : $filename;
133 if (empty($this->mimetype)) {
134 require_once 'File/MimeType.php';
135 $y = new File_MimeType();
136 $this->mimetype = $y->fromFilename($filename);
139 $this->mimetype = strtolower($this->mimetype);
141 $mta = explode('/', $this->mimetype);
142 if (array_shift($mta) == 'image') {
144 $imgs = @getimagesize($file);
146 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
149 list($this->width , $this->height) = $imgs;
153 if($this->mimetype == 'application/pdf'){
154 $this->no_of_pages = $this->getPdfPages($file);
157 $this->filesize = filesize($file);
158 $this->created = date('Y-m-d H:i:s');
161 if (empty($this->filename)) {
162 $this->filename = basename($filename);
165 //DB_DataObject::debugLevel(1);
174 $f = $this->getStoreName();
176 if (!file_exists($dest)) {
177 // currently this is 0775 due to problems using shared hosing (FTP)
178 // it makes all the files unaccessable..
179 // you can normally solve this by giving the storedirectory better perms
180 // if needed on a dedicated server..
181 $oldumask = umask(0);
182 mkdir($dest, 0775, true);
193 // $this->createThumbnail(0,50);
199 * Calculate target file name
201 * @return - target file name
203 function getStoreName()
205 $opts = HTML_FlexyFramework::get()->Pman;
206 $fn = preg_replace('/[^a-z0-9_\.]+/i', '_', $this->filename);
207 return implode( '/', array(
208 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
214 * does the files exist?
219 //var_dump($this->getStoreName());
220 return file_exists($this->getStoreName());
225 * deletes all the image instances of it...
229 function beforeDelete($dependants_array, $roo)
232 if (!empty($dependants_array)) {
236 $opts = HTML_FlexyFramework::get()->Pman;
237 $deldir = $opts['storedir']. '/_deleted_images_';
239 if (!file_exists( $deldir )) {
240 @mkdir($deldir, 0755); // not sure why we are erroring here.. after checking - maybe permissions?
243 $fn = $this->getStoreName();
245 if (file_exists($fn)) {
247 if (file_exists($deldir . '/'. $b)) {
250 rename($fn, $deldir .'/'. $b);
258 if (file_exists($d)) {
261 while (false !== ($fn = readdir($dh))) {
262 if (substr($fn, 0, strlen($b)) == $b) {
264 if (file_exists($deldir . '/'. $fn)) {
265 unlink($d. '/'. $fn);
268 rename($d. '/'. $fn, $deldir .'/'. $fn);
276 * check mimetype against type
277 * - eg. img.is(#image#)
282 if (empty($this->mimetype)) {
285 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
289 * onUpload (singlely attached image to a table)
292 function onUploadWithTbl($tbl, $fld)
294 if ( $tbl->__table == 'Images') {
295 return; // not upload to self...
297 if (empty($_FILES['imageUpload']['tmp_name']) ||
298 empty($_FILES['imageUpload']['name']) ||
299 empty($_FILES['imageUpload']['type'])
304 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
306 $image = DB_DataObject::factory('Images');
307 $image->get($tbl->$fld);
308 $image->beforeDelete();
312 $image = DB_DataObject::factory('Images');
313 $image->onid = $tbl->id;
314 $image->ontable = $tbl->__table;
315 $image->filename = $_FILES['imageUpload']['name'];
316 $image->mimetype = $_FILES['imageUpload']['type'];
318 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
322 $tbl->$fld = $image->id;
329 function onUpload($roo, $table = false, $file = false)
332 if ($table !== false) {
333 $this->ontable = $table->tableName();
334 $this->onid = $table->pid();
337 if ($file === false) {
338 $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
341 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
342 if (empty($file['tmp_name']) ||
343 empty($file['name']) ||
348 0=>"There is no error, the file uploaded with success",
349 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
350 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
351 3=>"The uploaded file was only partially uploaded",
352 4=>"No file was uploaded",
353 6=>"Missing a temporary folder"
355 $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
356 $this->err = "Missing file details : Error=". $estr;
361 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
363 $this->beforeDelete();
365 if ( empty($this->ontable)) {
366 $this->err = "Missing ontable";
370 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
371 // then its an upload
372 $img = DB_DataObject::factory('Images');
373 $img->onid = $this->onid;
374 $img->ontable = $this->ontable;
375 $img->imgtype = $this->imgtype;
378 while ($img->fetch()) {
379 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
381 $img->beforeDelete();
389 require_once 'File/MimeType.php';
390 $y = new File_MimeType();
391 $this->mimetype = $file['type'];
392 if (in_array($this->mimetype, array(
394 'application/octet-stream',
395 'image/x-png', // WTF does this?
396 'image/pjpeg', // WTF does this?
397 'application/x-apple-msg-attachment', /// apple doing it's magic...
398 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
399 'application/csv-tab-delimited-table', // windows again!!?
400 ))) { // weird tyeps..
401 $inf = pathinfo($file['name']);
402 $this->mimetype = $y->fromExt($inf['extension']);
406 $ext = $y->toExt(trim((string) $this->mimetype ));
408 $this->filename = empty($this->filename) ?
409 $file['name'] : ($this->filename .'.'. $ext);
413 if (!$this->createFrom($file['tmp_name'])) {
414 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
424 * return a list of images for an object, optionally with a mime regex.
425 * eg. '%/pdf' or 'image/%'
429 * $i = DB_DataObject::factory('Images');
430 * $i->imgtype = 'LOGO';
431 * $ar = $i->gather($somedataobject, 'image/%');
433 * @param {DB_DataObject} dataobject = the object to gather data on.
434 * @param {String} mimelike LIKE query to use for search
437 function gather($obj, $mime_like='', $opts=array())
439 //DB_DataObject::debugLevel(1);
440 if (empty($obj->id)) {
445 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
448 if (!empty($mime_like)) {
449 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
451 $c->orderBy('created DESC');
453 return $c->fetchAll();
458 * set or get the dataobject this image is associated with
459 * @param DB_DataObject $obj An object to associate this image with
460 * (does not store it - you need to call update() to do that)
461 * @return DB_DataObject the dataobject this image is attached to.
463 function object($obj=false)
465 if ($obj === false) {
466 if (empty($this->ontable) || empty($this->onid)) {
469 $ret = DB_DataObject::factory($this->ontable);
470 $ret->get($this->onid);
475 $this->ontable = $obj->tableName();
476 $this->onid = $obj->id; /// assumes our nice standard of using ids..
481 function toRooArray($req)
484 $ret= $this->toArray();
487 $ff = HTML_FlexyFramework::get();
490 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
491 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
493 if (!empty($req['query']['imagesize'])) {
494 // query/imageBaseURL ... depricated...? -- set it in config?
496 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
498 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
500 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
502 if (!empty($req['query']['imagesize'])) {
503 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
508 $ret['shorten_name'] = $this->shorten_name();
514 * URL - create a url for the image.
515 * size - use -1 to show full size.
516 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
520 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
523 return 'about:blank';
525 if (!$this->exists()) {
526 return 'about:missing';
529 $shorten_name = $this->shorten_name();
531 $ff = HTML_FlexyFramework::get();
532 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
533 if (preg_match('#^http[s]*://#', $provider)) {
538 $provider = preg_replace('#/Thumb$#', '', $provider);
540 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
543 //$size = max(100, (int) $size);
544 //$size = min(1024, (int) $size);
545 // the size should 200x150 to convert
546 $sizear = preg_split('/(x|c)/', $size);
547 if(!isset($sizear[1])){
548 $sizear[1] = 0; // 0x with '0' is a box? why
551 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
553 $fc = $this->toFileConvert();
556 $mt = $this->mimetype;
557 if (!preg_match('#^image/#i',$mt)) {
561 $fc->convert($mt, $size);
563 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
566 function getFromHashURL($url)
569 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
571 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
573 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
577 if ($id === false || $id < 1) {
581 $img = DB_DAtaObject::Factory('images');
582 if ($img->get($id)) {
589 function shorten_name()
591 if(empty($this->filename)) {
595 $filename = explode('.', $this->filename);
596 $ext = array_pop($filename);
597 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
599 if(strlen($name) > 32) {
600 $name = substr($name, 0, 32);
603 $shorten_name = "{$name}.{$ext}";
605 return $shorten_name;
608 * size could be 123x345
612 function toHTML($size, $provider = '/Images/Thumb', $extra = '')
617 $sz = explode('x', $size);
620 if (!$this->id || empty($this->width)) {
622 $this->width = empty($sz[1]) ? $sx : $sz[1];
626 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
627 $sy = intval($ratio * $sx);
633 if (strlen($this->title)) {
634 $extra = ' title="'. htmlspecialchars($this->title) . '"';
637 return '<img src="' . $this->URL($size, $provider) . '"' .
639 ' width="'. $sx . '"' .
640 ' height="'. $sy . '">';
647 * #2142 [new] CMS - image link urls
652 function toLinkHTML($size, $provider = '/Images/Thumb')
654 if(empty($this->linkurl)){
655 return $this->toHTML($size, $provider = '/Images/Thumb');
658 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
664 * to Fileconvert object..
669 function toFileConvert()
671 require_once 'File/Convert.php';
672 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
679 require_once 'File/MimeType.php';
681 $y = new File_MimeType();
682 return $y->toExt($this->mimetype);
694 function setFromRoo($ar, $roo)
696 // not sure why we do this..
698 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
699 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
702 if ($this->find(true)) {
703 $roo->old = clone($this);
708 if (!empty($ar['_copy_from'])) {
710 if (!$this->checkPerm( 'A' , $roo->authUser)) {
711 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
714 $copy = DB_DataObject::factory('Images');
715 $copy->get($ar['_copy_from']);
716 $this->setFrom($copy->toArray());
718 $this->createFrom($copy->getStoreName());
720 $roo->addEvent("ADD", $this, $this->toEventString());
722 $r = DB_DataObject::factory($this->tableName());
728 $roo->jok($r->toRooArray($ar));
735 // FIXME - we should be checking perms here...
737 // this should be doign update
740 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
741 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
745 if (!isset($_FILES['imageUpload'])) {
746 return; // standard update...
750 // print_r(!$this->onUpload($this));
752 if ( !$this->onUpload($this)) {
753 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
756 $this->addEvent($ar, $roo);
758 $r = DB_DataObject::factory($this->tableName());
763 $roo->jok($r->toRooArray($ar));
767 function addEvent($ar, $roo)
769 $roo->addEvent("ADD", $this, $this->toEventString());
772 function toEventString()
775 //$p = DB_DataObject::factory($this->ontable);
777 // return "ERROR unknown table? {$this->ontable}";
781 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
782 //$p->toEventString();
785 function onUploadFromData($data, $roo)
788 $this->err = "Missing file details";
793 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
795 $this->beforeDelete();
798 if (empty($this->ontable)) {
799 $this->err = "Missing ontable";
803 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
804 // then its an upload
805 $img = DB_DataObject::factory('Images');
806 $img->onid = $this->onid;
807 $img->ontable = $this->ontable;
808 $img->imgtype = $this->imgtype;
811 while ($img->fetch()) {
812 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
814 $img->beforeDelete();
820 require_once 'File/MimeType.php';
821 $y = new File_MimeType();
823 if (in_array($this->mimetype, array(
825 'application/octet-stream',
826 'image/x-png', // WTF does this?
827 'image/pjpeg', // WTF does this?
828 'application/x-apple-msg-attachment', /// apple doing it's magic...
829 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
830 'application/csv-tab-delimited-table', // windows again!!?
831 ))) { // weird tyeps..
832 $inf = pathinfo($this->filename);
833 $this->mimetype = $y->fromExt($inf['extension']);
836 $ext = $y->toExt(trim((string) $this->mimetype ));
838 $explode_filename = explode('.', $this->filename);
839 if(array_pop($explode_filename) != $ext){
840 $this->filename = $this->filename .'.'. $ext;
843 if (!$this->createFromData($data)) {
851 function createFromData($data)
854 if (0 === strpos($data, "data:")) {
855 // data:image/png;base64,
856 $data = substr($data,5);
857 $bits = explode(";", $data);
858 $this->mimetype = $bits[0];
861 if (empty($this->filename)) {
862 require_once 'File/MimeType.php';
863 $y = new File_MimeType();
864 $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
868 $this->mimetype = strtolower($this->mimetype);
869 if ($this->mimetype == 'image/jpg') {
870 $this->mimetype = 'image/jpeg';
874 $explode_mimetype = explode('/', $this->mimetype);
876 if (array_shift($explode_mimetype) == 'image') {
878 $imgs = @getimagesize('data://'. $data);
880 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
881 list($this->width , $this->height) = $imgs;
885 $this->created = date('Y-m-d H:i:s');
893 $f = $this->getStoreName();
895 if (!file_exists($dest)) {
896 $oldumask = umask(0);
897 mkdir($dest, 0775, true);
901 file_put_contents($f, file_get_contents("data://" . $data));
905 $this->filesize = filesize($f);
907 if($this->mimetype == 'application/pdf'){
908 $this->no_of_pages = $this->getPdfPages($f);
917 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
919 if(!preg_match('/^image\//', $this->mimetype)){
923 $file = $this->getStoreName();
925 if(!file_exists($file)){
929 $data = file_get_contents($file);
931 if(!empty($scaleWidth) || !empty($scaleHeight)){
932 $data = $this->scale(false, $scaleWidth, $scaleHeight);
936 $data = $this->rotate($data);
939 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
944 function getPdfPages($file)
946 require_once 'System.php';
950 $pdfinfo = System::which('pdfinfo');
952 if (!file_exists($file) || empty($pdfinfo)) {
956 $cmd = "{$pdfinfo} {$file}";
960 $info = explode("\n", $ret);
962 foreach ($info as $i){
964 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
968 $page = (empty($matches[1])) ? 0 : $matches[1];
974 function rotate($imageBlob = false)
976 if(empty($imageBlob)){
977 $imagick = new Imagick($this->getStoreName());
979 $imagick = new Imagick();
980 $imagick->readImageBlob($imageBlob);
983 $orientation = $imagick->getImageOrientation();
985 switch($orientation) {
986 case Imagick::ORIENTATION_BOTTOMRIGHT:
987 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
990 case Imagick::ORIENTATION_RIGHTTOP:
991 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
994 case Imagick::ORIENTATION_LEFTBOTTOM:
995 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
999 return $imagick->getImageBlob();
1002 function scale($imageBlob = false, $width = 0, $height = 0)
1004 if(empty($imageBlob)){
1005 $imagick = new Imagick($this->getStoreName());
1007 $imagick = new Imagick();
1008 $imagick->readImageBlob($imageBlob);
1011 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
1013 return $imagick->getImageBlob();