File: class.datei.php

package info (click to toggle)
collabtive 0.7.6-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 13,968 kB
  • sloc: php: 63,984; sh: 101; makefile: 40
file content (688 lines) | stat: -rw-r--r-- 23,522 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
<?php
/**
 * class datei (file) provides methods to handle files and folders
 *
 * @author Open Dynamics / Philipp Kiszka <info@o-dyn.de>
 * @name datei
 * @version 0.7
 * @package Collabtive
 * @link http://www.o-dyn.de
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License v3 or later
 */
class datei {
    /**
     * Constructor
     * Initialize the event log
     */
    function __construct()
    {
        $this->mylog = new mylog;
    }
    // FOLDER METHODS
    /**
     * Create a new folder
     *
     * @param int $project Project ID the folder belongs to
     * @param string $folder Name of the new folder
     * @param string $desc Description of the folder
     * @return bool
     */
    function addFolder($parent, $project, $folder, $desc, $visible = "")
    {
        $project = (int) $project;
        $folder = mysql_real_escape_string($folder);
        $folderOrig = $folder;
        $desc = mysql_real_escape_string($desc);
        if (!empty($visible)) {
            $visstr = serialize($visible);
        } else {
            $visstr = "";
        }

        $folder = str_replace("ä", "ae" , $folder);
        $folder = str_replace("ö", "oe" , $folder);
        $folder = str_replace("ü", "ue" , $folder);
        $folder = str_replace("ß", "ss" , $folder);
        // remove whitespace
        $folder = preg_replace("/\W/", "", $folder);
        $folder = preg_replace("/[^-_0-9a-zA-Z]/", "_", $folder);
        // insert the folder into the db
        $ins = mysql_query("INSERT INTO projectfolders (parent,project,name,description,visible) VALUES ($parent,$project,'$folder','$desc','$visstr')");
        if ($ins) {
            // create the folder
            $makefolder = CL_ROOT . "/files/" . CL_CONFIG . "/$project/$folder/";
            if (!file_exists($makefolder)) {
                if (mkdir($makefolder, 0777, true)) {
                    // folder created
                    $this->mylog->add($folderOrig, 'folder', 1, $project);
                    return true;
                }
            } else {
                // folder already existed, return false
                return false;
            }
        } else {
            // folder wasnt created , return false
            return false;
        }
    }

    /**
     * Delete a folder
     * Deletes the given folder with all files in it and all of its subfolders.
     *
     * @param int $id folder id
     * @param int $id project id
     * @return bool
     */
    function deleteFolder($id, $project)
    {
        $id = (int) $id;
        $folder = $this->getFolder($id);
        $files = $this->getProjectFiles($project, 10000, $id);
        // delete all the files in the folder from the database (and filesystem as well)
        foreach($files as $file) {
            $this->loeschen($file["ID"]);
        }
        if (!empty($folder["subfolders"])) {
            foreach($folder["subfolders"] as $sub) {
                $this->deleteFolder($sub["ID"], $sub["project"]);
            }
        }
        $del = mysql_query("DELETE FROM projectfolders WHERE ID = $id");
        if ($del) {
            // remove directory
            $foldstr = CL_ROOT . "/files/" . CL_CONFIG . "/$project/" . $folder["name"] . "/";
            delete_directory($foldstr);
            $this->mylog->add($folder["name"], 'folder', 3, $project);
            return true;
        }
    }

    /**
     * Get directory
     *
     * @param string $id Directory
     * @return array $files Found files and directories
     */
    function getFolder($id)
    {
        $id = (int) $id;
        $sel = mysql_query("SELECT * FROM projectfolders WHERE ID = $id LIMIT 1");
        $folder = mysql_fetch_array($sel);
        $folder["subfolders"] = $this->getSubFolders($folder["ID"]);
        $folder["abspath"] = $this->getAbsolutePathName($folder);

        return $folder;
    }

    /**
     * Recursively get subdirectories of a given directory
     *
     * @param int $id Directory
     * @return array $files Found files and directories
     */
    function getSubFolders($parent)
    {
        $parent = (int) $parent;
        $sel = mysql_query("SELECT * FROM projectfolders WHERE parent = $parent ORDER BY ID ASC");

        $folders = array();

        while ($folder = mysql_fetch_array($sel)) {
            $folder["subfolders"] = $this->getSubFolders($folder["ID"]);
            $folder["abspath"] = $this->getAbsolutePathName($folder);
            array_push($folders, $folder);
        }

        if (!empty($folders)) {
            return $folders;
        } else {
            return false;
        }
    }

    /**
     * Get all the directories in a project
     *
     * @param string $id project Project ID
     * @return array $files Found files and directories
     */
    function getProjectFolders($project, $parent = 0)
    {
        $project = (int) $project;

        $sel = mysql_query("SELECT * FROM projectfolders WHERE project = $project AND parent = $parent ORDER BY ID ASC");
        $folders = array();

        while ($folder = mysql_fetch_array($sel)) {
            $folder["subfolders"] = $this->getSubFolders($folder["ID"]);
            $folder["abspath"] = $this->getAbsolutePathName($folder);
            array_push($folders, $folder);
        }

        if (!empty($folders)) {
            return $folders;
        } else {
            return false;
        }
    }

    /**
     * Get all the directories in a project
     *
     * @param string $id project Project ID
     * @return array $files Found files and directories
     */
    function getAllProjectFolders($project)
    {
        $project = (int) $project;

        $sel = mysql_query("SELECT * FROM projectfolders WHERE project = $project ORDER BY ID ASC");
        $folders = array();

        while ($folder = mysql_fetch_array($sel)) {
            $folder["subfolders"] = $this->getSubFolders($folder["ID"]);
            $folder["abspath"] = $this->getAbsolutePathName($folder);
            array_push($folders, $folder);
        }

        if (!empty($folders)) {
            return $folders;
        } else {
            return false;
        }
    }

    /**
     * Get Absolute Path Name
     * Returns the absolute name (relative to the root-directory of the project) of a folder.
     *
     * @param array $folder The folder to be inspected
     * @return string absolute path/name of the folder
     */
    function getAbsolutePathName($folder)
    {
        if ($folder['parent'] == 0) {
            return "/" . $folder['name'];
        } else {
            $sel = mysql_query("SELECT * FROM projectfolders WHERE ID = " . $folder['parent']);
            $parent = mysql_fetch_array($sel);

            return $this->getAbsolutePathName($parent) . "/" . $folder['name'];
        }
    }
    // FILE METHODS
    /**
     * Upload a file
     * Does filename sanitizing as well as MIME-type determination
     * Also adds the file to the database using add_file()
     *
     * @param string $fname Name of the HTML form field POSTed from
     * @param string $ziel Destination directory
     * @param int $project Project ID of the associated project
     * @return bool
     */
    function upload($fname, $ziel, $project, $folder = 0)
    {
        $name = $_FILES[$fname]['name'];
        $typ = $_FILES[$fname]['type'];
        $size = $_FILES[$fname]['size'];
        $tmp_name = $_FILES[$fname]['tmp_name'];
        $tstr = $fname . "-title";
        $tastr = $fname . "-tags";
        $visible = $_POST["visible"];

        if (!empty($visible[0])) {
            $visstr = serialize($visible);
        } else {
            $visstr = "";
        }

        $title = $_POST[$tstr];
        $tags = $_POST[$tastr];
        $error = $_FILES[$fname]['error'];
        $root = CL_ROOT;

        if (empty($name)) {
            return false;
        }

        $desc = $_POST['desc'];

        $tagobj = new tags();
        $tags = $tagobj->formatInputTags($tags);
        // find the extension
        $teilnamen = explode(".", $name);
        $teile = count($teilnamen);
        $workteile = $teile - 1;
        $erweiterung = $teilnamen[$workteile];
        $subname = "";
        // if its a php file, treat it as plaintext so its not executed when opened in the browser.
        if (stristr($erweiterung, "php")) {
            $erweiterung = "txt";
            $typ = "text/plain";
        }

        for ($i = 0; $i < $workteile; $i++) {
            $subname .= $teilnamen[$i];
        }

        $randval = mt_rand(1, 99999);
        // only allow a-z , 0-9 in filenames, substitute other chars with _
        $subname = str_replace("ä", "ae" , $subname);
        $subname = str_replace("ö", "oe" , $subname);
        $subname = str_replace("ü", "ue" , $subname);
        $subname = str_replace("ß", "ss" , $subname);
        $subname = preg_replace("/[^-_0-9a-zA-Z]/", "_", $subname);
        // remove whitespace
        $subname = preg_replace("/\W/", "", $subname);
        // if filename is longer than 200 chars, cut it.
        if (strlen($subname) > 200) {
            $subname = substr($subname, 0, 200);
        }

	// don't allow file extensions that can often be executed by
	// the server - PHP is often associated with *.php, *.php3,
	// *.phtml, *.phps
	if (preg_match($erweiterung, "/^(php|phtml)/")) {
	  $erweiterung = '_' . $erweiterung;
	}

        $name = $subname . "_" . $randval . "." . $erweiterung;
        $datei_final = $root . "/" . $ziel . "/" . $name;
        $datei_final2 = $ziel . "/" . $name;

        if (!file_exists($datei_final)) {
            if (move_uploaded_file($tmp_name, $datei_final)) {
                // $filesize = filesize($datei_final);
                if ($project > 0) {
                    /**
                     * file did not already exist, was uploaded, and a project is set
                     * add the file to the database, add the upload event to the log and return the file ID.
                     */
                    chmod($datei_final, 0755);
                    $fid = $this->add_file($name, $desc, $project, 0, "$tags", $datei_final2, "$typ", $title, $folder, $visstr);
                    if (!empty($title)) {
                        $this->mylog->add($title, 'file', 1, $project);
                    } else {
                        $this->mylog->add($name, 'file', 1, $project);
                    }
                    return $fid;
                } else {
                    // no project means the file is not added to the database wilfully. return file name.
                    return $name;
                }
            } else {
                // file was not uploaded / error occured. return false
                return false;
            }
        } else {
            // file already exists. return false
            return false;
        }
    }
  /**
     * Upload a file
     * Does filename sanitizing as well as MIME-type determination
     * Also adds the file to the database using add_file()
     *
     * @param string $fname Name of the HTML form field POSTed from
     * @param string $ziel Destination directory
     * @param int $project Project ID of the associated project
     * @return bool
     */
    function uploadAsync($name,$tmp_name,$typ,$size,$ziel, $project, $folder = 0)
    {
        $visible = "";
        $visstr = "";
        $root = CL_ROOT;

        if (empty($name)) {
            return false;
        }

        // find the extension
        $teilnamen = explode(".", $name);
        $teile = count($teilnamen);
        $workteile = $teile - 1;
        $erweiterung = $teilnamen[$workteile];
        $subname = "";
        // if its a php file, treat it as plaintext so its not executed when opened in the browser.
        if (stristr($erweiterung, "php")) {
            $erweiterung = "txt";
            $typ = "text/plain";
        }

        for ($i = 0; $i < $workteile; $i++) {
            $subname .= $teilnamen[$i];
        }

        $randval = mt_rand(1, 99999);
        // only allow a-z , 0-9 in filenames, substitute other chars with _
        $subname = str_replace("ä", "ae" , $subname);
        $subname = str_replace("ö", "oe" , $subname);
        $subname = str_replace("ü", "ue" , $subname);
        $subname = str_replace("ß", "ss" , $subname);
        $subname = preg_replace("/[^-_0-9a-zA-Z]/", "_", $subname);
        // remove whitespace
        $subname = preg_replace("/\W/", "", $subname);
        // if filename is longer than 200 chars, cut it.
        if (strlen($subname) > 200) {
            $subname = substr($subname, 0, 200);
        }

        $name = $subname . "_" . $randval . "." . $erweiterung;
        $datei_final = $root . "/" . $ziel . "/" . $name;
        $datei_final2 = $ziel . "/" . $name;

        if (!file_exists($datei_final)) {
            if (move_uploaded_file($tmp_name, $datei_final)) {
                // $filesize = filesize($datei_final);
                if ($project > 0) {
                    /**
                     * file did not already exist, was uploaded, and a project is set
                     * add the file to the database, add the upload event to the log and return the file ID.
                     */
                    chmod($datei_final, 0755);
                    $fid = $this->add_file($name, $desc, $project, 0, "$tags", $datei_final2, "$typ", $title, $folder, $visstr);
                    if (!empty($title)) {
                        $this->mylog->add($title, 'file', 1, $project);
                    } else {
                        $this->mylog->add($name, 'file', 1, $project);
                    }
                    return $fid;
                } else {
                    // no project means the file is not added to the database wilfully. return file name.
                    return $name;
                }
            } else {
                // file was not uploaded / error occured. return false
                return false;
            }
        } else {
            // file already exists. return false
            return false;
        }
    }
    /**
     * Edit a file
     *
     * @param int $id File ID
     * @param string $title Title of the file
     * @param string $desc Description text
     * @param string $tags Associated tags (not yet implemented)
     * @return bool
     */
    function edit($id, $title, $desc, $tags)
    {
        $id = (int) $id;
        $title = mysql_real_escape_string($title);
        $desc = mysql_real_escape_string($desc);
        $tags = mysql_real_escape_string($tags);
        // get project for logging
        $sel = mysql_query("SELECT project FROM files WHERE ID = $id");
        $proj = mysql_fetch_row($sel);
        $project = $proj[0];

        $sql = mysql_query("UPDATE files SET `title` = '$title', `desc` = '$desc', `tags` = '$tags' WHERE id = $id");
        if ($sql) {
            $this->mylog->add($title, 'file' , 2, $project);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Delete a file
     *
     * @param int $datei File ID
     * @return bool
     */
    function loeschen($datei)
    {
        $datei = (int) $datei;

        $sel1 = mysql_query("SELECT datei,name,project,title FROM files WHERE ID = $datei");
        $thisfile = mysql_fetch_row($sel1);
        if (!empty($thisfile)) {
            $fname = $thisfile[1];
            $project = $thisfile[2];
            $ftitle = $thisfile[3];
            $thisfile = $thisfile[0];

            $delfile = "./" . $thisfile;

            if (!file_exists($delfile)) {
                return false;
            }
            $del = mysql_query("DELETE FROM files WHERE ID = $datei");
            $del2 = mysql_query("DELETE FROM files_attached WHERE file = $datei");
            if ($del) {
                if (unlink($delfile)) {
                    if ($ftitle != "") {
                        $this->mylog->add($ftitle, 'file', 3, $project);
                    } else {
                        $this->mylog->add($fname, 'file', 3, $project);
                    }
                    return true;
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }

    /**
     * Return a file
     *
     * @param string $id File ID
     * @return array $file File details
     */

    function getFile($id)
    {
        $id = (int) $id;
        // get the file from MySQL
        $sel = mysql_query("SELECT * FROM files WHERE ID=$id");
        $file = mysql_fetch_array($sel);

        if (!empty($file)) {
            // determine if there is an mimetype icon corresponding to the files mimetype. If not set 'none'
            $file['type'] = str_replace("/", "-", $file["type"]);

            $set = new settings();
            $settings = $set->getSettings();
            $myfile = "./templates/" . $settings["template"] . "/images/files/" . $file['type'] . ".png";
            if (!file_exists($myfile)) {
                $file['type'] = "none";
            }
            // determine if its an image or textfile or some other file. this is needed for lightboxes
            if (stristr($file['type'], "image")) {
                $file['imgfile'] = 1;
            } elseif (stristr($file['type'], "text")) {
                $file['imgfile'] = 2;
            } else {
                $file['imgfile'] = 0;
            }
            // split the tags string into an array, and also count how many tags the file has
            $tagobj = new tags();
            $thetags = $tagobj->splitTagStr($file["tags"]);;
            $file["tagsarr"] = $thetags;
            $file["tagnum"] = count($file["tagsarr"]);
            // strip slashes from titles , desc and tags
            $file["title"] = stripslashes($file["title"]);
            $file["desc"] = stripslashes($file["desc"]);
            $file["tags"] = stripslashes($file["tags"]);
            $file["size"] = filesize(realpath($file["datei"])) / 1024;
            $file["size"] = round($file["size"]);
            $file["addedstr"] = date("d.m.y", $file["added"]);
            $userobj = new user();
            $file["userdata"] = $userobj->getProfile($file["user"]);

            return $file;
        } else {
            return false;
        }
    }

    /**
     * Move a file to another folder
     *
     * @param int $file File ID
     * @param int $folder Folder ID
     * @return bool
     */
    function moveFile($file, $target)
    {
        $file = (int) $file;
        $target = (int)$target;
        // Get the file
        $thefile = $this->getFile($file);
        // Get the target folder
        $thefolder = $this->getFolder($target);
        // Build filesystem paths
        $targetstr = "files/" . CL_CONFIG . "/" . $thefile["project"] . "/" . $thefolder["name"] . "/" . $thefile["name"];
        $rootstr = CL_ROOT . "/" . $thefile["datei"];
        // update database
        $upd = mysql_query("UPDATE files SET datei = '$targetstr', folder = '$thefolder[ID]' WHERE ID = $thefile[ID]");
        // move the file physically
        return rename($rootstr, $targetstr);
    }

    /**
     * List all files associated to a given project
     *
     * @param string $id Project ID
     * @param int $lim Limit
     * @param int $folder Folder
     * @return array $files Found files
     */
    function getProjectFiles($id, $lim = 25, $folder = "")
    {
        $id = (int) $id;
        $lim = (int) $lim;
        $folder = (int) $folder;

        if ($folder > 0) {
            $fold = "files/" . CL_CONFIG . "/$id/$folder/";
            $sel = mysql_query("SELECT COUNT(*) FROM files WHERE project = $id AND folder = $folder ORDER BY ID DESC");
        } else {
            $sel = mysql_query("SELECT COUNT(*) FROM files WHERE project = $id AND folder = 0 ORDER BY ID DESC");
        }
        $num = mysql_fetch_row($sel);
        $num = $num[0];
        SmartyPaginate::connect();
        // set items per page
        SmartyPaginate::setLimit($lim);
        SmartyPaginate::setTotal($num);

        $start = SmartyPaginate::getCurrentIndex();
        $lim = SmartyPaginate::getLimit();

        $files = array();

        if ($folder > 0) {
            $sql = "SELECT ID FROM files WHERE project = $id AND folder = $folder ORDER BY  ID DESC LIMIT $start,$lim";
            $sel2 = mysql_query($sql);
        } else {
            $sel2 = mysql_query("SELECT ID FROM files WHERE project = $id AND folder = 0 ORDER BY  ID DESC LIMIT $start,$lim");
        } while ($file = mysql_fetch_array($sel2)) {
            if (!empty($file)) {
                array_push($files, $this->getFile($file["ID"]));
            }
        }

        if (!empty($files)) {
            return $files;
        } else {
            return false;
        }
    }

    /**
     * List all files associated to a given project
     *
     * @param string $id Project ID
     * @param int $lim Limit
     * @param int $folder Folder
     * @return array $files Found files
     */
    function getAllProjectFiles($id)
    {
        $id = (int) $id;
        $lim = (int) $lim;
        $folder = (int) $folder;

        $files = array();

        $sel2 = mysql_query("SELECT ID FROM files WHERE project = $id  ORDER BY  ID DESC");

        while ($file = mysql_fetch_array($sel2)) {
            if (!empty($file)) {
                array_push($files, $this->getFile($file["ID"]));
            }
        }

        if (!empty($files)) {
            return $files;
        } else {
            return false;
        }
    }

    /**
     * Seed the random number generator
     *
     * @return float $value Initial value
     */
    private function make_seed()
    {
        list($usec, $sec) = explode(' ', microtime());
        $value = (float) $sec + ((float) $usec * 100000);
        return $value;
    }

    /**
     * Add a file to the database
     *
     * @param string $name Filename
     * @param string $desc Description
     * @param int $project ID of the associated project
     * @param int $milestone ID of the associated milestone
     * @param string $tags Tags for the file (not yet implemented)
     * @param string $datei File path
     * @param string $type MIME Type
     * @param string $title Title of the file
     * @param int $ folder Optional parameter. It holds the ID of the subfolder the file is uploaded to (0 = root directory)
     * @return bool $insid
     */
    private function add_file($name, $desc, $project, $milestone, $tags, $datei, $type, $title, $folder = 0, $visstr = "")
    {
        $name = mysql_real_escape_string($name);
        $desc = mysql_real_escape_string($desc);
        $tags = mysql_real_escape_string($tags);
        $datei = mysql_real_escape_string($datei);
        $project = (int) $project;
        $milestone = (int) $milestone;
        $folder = (int) $folder;
        $userid = $_SESSION["userid"];
        $type = mysql_real_escape_string($type);
        $title = mysql_real_escape_string($title);
        $now = time();

        $ins = mysql_query("INSERT INTO files (`name`,`desc`,`project`,`milestone`,`user`,`tags`,`added`,`datei`,`type`,`title`,`folder`,`visible`) VALUES ('$name','$desc',$project,$milestone,$userid,'$tags','$now','$datei','$type','$title','$folder','$visstr')");

        if ($ins) {
            $insid = mysql_insert_id();
            return $insid;
        } else {
            return false;
        }
    }
}

?>