Welcome to mirror list, hosted at ThFree Co, Russian Federation.

functions-manager.php « server - github.com/jappix/jappix.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c879937f860399444e5f4bb00781f448fa64ce96 (plain)
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
<?php

/*

Jappix - An open social platform
These are the PHP functions for Jappix manager

-------------------------------------------------

License: AGPL
Authors: Valérian Saliou, Mathieui, olivierm, Vinilox, regilero, Cyril "Kyriog" Glapa

*/

// The function to check an user is admin
function isAdmin($user, $password) {
    // Read the users.xml file
    $array = getUsers();

    // No data?
    if(empty($array)) {
        return false;
    }

    // Our user is set and valid?
    if(isset($array[$user]) && ($array[$user] == $password)) {
        return true;
    }

    // Not authorized
    return false;
}

// Checks if a file is a valid image
function isImage($file) {
    // This is an image
    if(preg_match('/^(.+)(\.)(png|jpg|jpeg|gif|bmp)$/i', $file)) {
        return true;
    }

    return false;
}

// Puts a marker on the current opened manager tab
function currentTab($current, $page) {
    if($current == $page) {
        echo ' class="tab-active"';
    }
}

// Checks all the storage folders are writable
function storageWritable() {
    // Read the directory content
    $dir = JAPPIX_BASE.'/store/';
    $scan = scandir($dir);

    // Writable marker
    $writable = true;

    // Check that each folder is writable
    foreach($scan as $current) {
        // Current folder
        $folder = $dir.$current;

        // A folder is not writable?
        if(!preg_match('/^\.(.+)/', $current) && !is_writable($folder)) {
            // Try to change the folder rights
            chmod($folder, 0777);

            // Check it again!
            if(!is_writable($folder)) {
                $writable = false;
            }
        }
    }

    return $writable;
}

// Removes a given directory (with all sub-elements)
function removeDir($dir) {
    // Can't open the dir
    if(!$dh = @opendir($dir)) {
        return;
    }

    // Loop the current dir to remove its content
    while(false !== ($obj = readdir($dh))) {
        // Not a "real" directory
        if(($obj == '.') || ($obj == '..')) {
            continue;
        }

        // Not a file, remove this dir
        if(!@unlink($dir.'/'.$obj)) {
            removeDir($dir.'/'.$obj);
        }
    }

    // Close the dir and remove it!
    closedir($dh);
    @rmdir($dir);
}

// Copies a given directory (with all sub-elements)
function copyDir($source, $destination) {
    // This is a directory
    if(is_dir($source)) {
        // Create the target directory
        @mkdir($destination);
        $directory = dir($source);

        // Append the source directory content into the target one
        while(FALSE !== ($readdirectory = $directory->read())) {
            if(($readdirectory == '.') || ($readdirectory == '..')) {
                continue;
            }

            $PathDir = $source.'/'.$readdirectory;

            // Recursive copy
            if(is_dir($PathDir)) {
                copyDir($PathDir, $destination.'/'.$readdirectory);
                continue;
            }

            copy($PathDir, $destination.'/'.$readdirectory);
        }

        // Close the source directory
        $directory->close();
    }

    // This is a file
    else
        copy($source, $destination);
}

// Gets the total size of a directory
function sizeDir($dir) {
    $size = 0;

    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $file) {
        $size += $file->getSize();
    }

    return $size;
}

// Set the good unity for a size in bytes
function numericToMonth($id) {
    $array = array(
                1 => T_("January"),
                2 => T_("February"),
                3 => T_("March"),
                4 => T_("April"),
                5 => T_("May"),
                6 => T_("June"),
                7 => T_("July"),
                8 => T_("August"),
                9 => T_("September"),
                10 => T_("October"),
                11 => T_("November"),
                12 =>T_( "December")
              );

    return $array[$id];
}

// Extracts the version number with a version ID
function versionNumber($id) {
    // First, extract the number string from the [X]
    $extract = preg_replace('/^(.+)\[(\S+)\]$/', '$2', $id);
    $dev = false;

    // Second extract: ~ (when this is a special version, like ~dev)
    if(strrpos($extract, '~') !== false) {
        $dev = true;
        $extract = preg_replace('/^([^~])~(.+)$/', '$1', $extract);
    }

    // Convert [X.X.X] into a full number
    $extract = preg_replace('/[^0-9]/', '', $extract);

    // Add missing items to [X.X.X]
    $missing = 3 - strlen($extract.'');
    if($missing > 0) {
        $extract = $extract.(str_repeat('0', $missing));
    }

    // Allows updates for dev versions
    if($dev) {
        $extract = $extract - 1;
    }

    return intval($extract);
}

// Checks for new Jappix updates
function newUpdates($force) {
    // No need to check if developer mode
    if(isDeveloper()) {
        return false;
    }

    $cache_path = JAPPIX_BASE.'/tmp/cache/version.xml';

    // No cache, obsolete one or refresh forced
    if(!file_exists($cache_path) || (file_exists($cache_path) && (time() - (filemtime($cache_path)) >= 86400)) || $force) {
        // Get the content
        $last_version = readUrl('https://project.jappix.com/xml/version.xml');

        // Write the content
        file_put_contents($cache_path, $last_version, LOCK_EX);
    } else {
        // Read from cache
        $last_version = file_get_contents($cache_path);
    }

    // Parse the XML
    $xml = @simplexml_load_string($last_version);

    // No data?
    if($xml === FALSE) {
        return false;
    }

    // Get the version numbers
    $current_version = getVersion();
    $last_version = $xml->id;

    // Check if we have the latest version
    $current_version = versionNumber($current_version);
    $last_version = versionNumber($last_version);

    if($current_version < $last_version) {
        return true;
    }

    return false;
}

// Gets the Jappix update informations
function updateInformations() {
    // Get the XML file content
    $data = file_get_contents(JAPPIX_BASE.'/tmp/cache/version.xml');

    // Transform the XML content into an array
    $array = array();

    // No XML?
    if(!$data) {
        return $array;
    }

    $xml = new SimpleXMLElement($data);

    // Parse the XML to add it to the array
    foreach($xml->children() as $this_child) {
        // Get the node name
        $current_name = $this_child->getName();

        // Push it to the array, with a basic HTML encoding
        $array[$current_name] = str_replace('\n', '<br />', (string)$this_child);
    }

    // Return this array
    return $array;
}

// Processes the Jappix update from an external package
function processUpdate($url) {
    // Archive path
    $name = md5($url).'.zip';
    $update_dir = JAPPIX_BASE.'/store/update/';
    $path = $update_dir.$name;
    $extract_to = $update_dir.'jappix/';
    $store_tree = JAPPIX_BASE.'/server/store-tree.php';

    // We must get the archive from the server
    if(!file_exists($path)) {
        echo('<p>» '.T_("Downloading package...").'</p>');

        // Create SSL request context
        $ssl_context = requestContext($url);

        // Open the packages
        $local = fopen($path, 'w');
        $remote = fopen($url, 'r', false, $ssl_context);

        // Could not open a socket?!
        if(!$remote) {
            echo('<p>» '.T_("Aborted: socket error!").'</p>');

            // Remove the broken local archive
            unlink($path);

            return false;
        }

        // Read the file
        while(!feof($remote)) {
            // Get the buffer
            $buffer = fread($remote, 1024);

            // Any error?
            if($buffer == 'Error.') {
                echo('<p>» '.T_("Aborted: buffer error!").'</p>');

                // Remove the broken local archive
                unlink($path);

                return false;
            }

            // Write the buffer to the file
            fwrite($local, $buffer);

            // Flush the current buffer
            flush();
        }

        // Close the files
        fclose($local);
        fclose($remote);
    }

    // Then, we extract the archive
    echo('<p>» '.T_("Extracting package...").'</p>');

    try {
        $zip = new ZipArchive;
        $zip_open = $zip->open($path);

        if($zip_open === TRUE) {
            $zip->extractTo($update_dir);
            $zip->close();
        } else {
            echo('<p>» '.T_("Aborted: could not extract the package!").'</p>');

            // Remove the broken source folder
            removeDir($to_remove);

            return false;
        }
    }

    // PHP does not provide Zip archives support
    catch(Exception $e) {
        echo('<p>» '.T_("Aborted: could not extract the package!").'</p>');

        // Remove the broken source folder
        removeDir($to_remove);

        return false;
    }

    // Remove the ./store dir from the source directory
    removeDir($extract_to.'store/');

    // Then, we remove the Jappix system files
    echo('<p>» '.T_("Removing current Jappix system files...").'</p>');

    // Open the general directory
    $dir_base = JAPPIX_BASE.'/';
    $scan = scandir($dir_base);

    // Filter the scan array
    $scan = array_diff($scan, array('.', '..', '.git', 'store'));

    // Check all the files are writable
    foreach($scan as $scanned) {
        // Element path
        $scanned_current = $dir_base.$scanned;

        // Element not writable
        if(!is_writable($scanned_current)) {
            // Try to change the element rights
            chmod($scanned_current, 0777);

            // Check it again!
            if(!is_writable($scanned_current)) {
                echo('<p>» '.T_("Aborted: everything is not writable!").'</p>');

                return false;
            }
        }
    }

    // Process the files deletion
    foreach($scan as $current) {
        $to_remove = $dir_base.$current;

        // Remove folders
        if(is_dir($to_remove)) {
            removeDir($to_remove);
        } else {
            // Remove files
            unlink($to_remove);
        }
    }

    // Move the extracted files to the base
    copyDir($extract_to, $dir_base);

    // Remove the source directory
    removeDir($extract_to);

    // Regenerates the store tree
    if(file_exists($store_tree)) {
        echo('<p>» '.T_("Regenerating storage folder tree...").'</p>');

        // Call the special regeneration script
        include($store_tree);
    }

    // Remove the version package
    unlink($path);

    // The new version is now installed!
    echo('<p>» '.T_("Jappix is now up to date!").'</p>');

    return true;
}

// Returns an array with the biggest share folders
function shareStats() {
    // Define some stuffs
    $path = JAPPIX_BASE.'/store/share/';
    $array = array();

    // Open the directory
    $scan = scandir($path);

    // Loop the share files
    foreach($scan as $current) {
        if(is_dir($path.$current) && !preg_match('/^(\.(.+)?)$/i', $current)) {
            array_push($array, $current);
        }
    }

    return $array;
}

// Returns the largest share folders
function largestShare($array, $number) {
    // Define some stuffs
    $path = JAPPIX_BASE.'/store/share/';
    $size_array = array();

    // Push the results in an array
    foreach($array as $current) {
        $size_array[$current] = sizeDir($path.$current);
    }

    // Sort this array
    arsort($size_array);

    // Select the first biggest values
    $size_array = array_slice($size_array, 0, $number);

    return $size_array;
}

// Returns the others statistics array
function otherStats() {
    // Fill the array with the values
    $others_stats = array(
                    T_("Backgrounds") => sizeDir(JAPPIX_BASE.'/store/backgrounds/'),
                    T_("Archives") => sizeDir(JAPPIX_BASE.'/tmp/archives/'),
                    T_("Music") => sizeDir(JAPPIX_BASE.'/store/music/'),
                    T_("Share") => sizeDir(JAPPIX_BASE.'/store/share/'),
                    T_("Send") => sizeDir(JAPPIX_BASE.'/tmp/send/'),
                 );

    // Sort this array
    arsort($others_stats);

    return $others_stats;
}

// Gets the array of the visits stats
function getVisits() {
    // New array
    $array = array(
                'total' => 0,
                'daily' => 0,
                'weekly' => 0,
                'monthly' => 0,
                'yearly' => 0
              );

    // Read the data
    $data = readXML('access', 'total');

    // Any data?
    if($data) {
        // Initialize the visits reading
        $xml = new SimpleXMLElement($data);

        // Get the XML values
        $array['total'] = intval($xml->total);
        $array['stamp'] = intval($xml->stamp);

        // Get the age of the stats
        $age = time() - $array['stamp'];

        // Generate the time-dependant values
        $timed = array(
                    'daily' => 86400,
                    'weekly' => 604800,
                    'monthly' => 2678400,
                    'yearly' => 31536000
                  );

        foreach($timed as $timed_key => $timed_value) {
            if($age >= $timed_value) {
                $array[$timed_key] = intval($array['total'] / ($age / $timed[$timed_key])).'';
            } else {
                $array[$timed_key] = $array['total'].'';
            }
        }
    }

    return $array;
}

// Gets the array of the monthly visits
function getMonthlyVisits() {
    // New array
    $array = array();

    // Read the data
    $data = readXML('access', 'months');

    // Get the XML file values
    if($data) {
        // Initialize the visits reading
        $xml = new SimpleXMLElement($data);

        // Loop the visit elements
        foreach($xml->children() as $child) {
            // Get the current month ID
            $current_id = intval(preg_replace('/month_([0-9]+)/i', '$1', $child->getName()));

            // Get the current month name
            $current_name = numericToMonth($current_id);

            // Push it!
            $array[$current_name] = intval((string)$child);
        }
    }

    return $array;
}

// Returns the folder path
function pathFolder($folder) {
    if($folder == 'archives' || $folder == 'avatar' ||
       $folder == 'cache'    || $folder == 'jingle' ||
       $folder == 'send') {
        return JAPPIX_BASE.'/tmp/'.$folder.'/';
    }

    return JAPPIX_BASE.'/store/'.$folder.'/';
}

// Purges the target folder content
function purgeFolder($folder) {
    // Array of the folders to purge
    $array = array();

    // We must purge all the folders?
    if($folder == 'everything') {
        array_push($array, 'archives', 'send');
    } else {
        array_push($array, $folder);
    }

    // All right, now we can empty it!
    foreach($array as $current_folder) {
        // Scan the current directory
        $directory = pathFolder($current_folder);
        $scan = scandir($directory);
        $scan = array_diff($scan, array('.', '..', '.svn', 'index.html'));

        // Process the files deletion
        foreach($scan as $current) {
            $remove_this = $directory.$current;

            if(is_dir($remove_this)) {
                // Remove folders
                removeDir($remove_this);
            } else {
                // Remove files
                unlink($remove_this);
            }
        }
    }
}

// Returns folder browsing informations
function browseFolder($folder, $mode) {
    // Scan the target directory
    $directory = pathFolder($folder);
    $scan = scandir($directory);
    $scan = array_diff($scan, array('.', '..', '.git', 'index.html'));
    $keep_get = keepGet('(s|b|k)', false);

    // Odd/even marker
    $marker = 'odd';

    // Not in the root folder: show previous link
    if(strpos($folder, '/') != false) {
        // Filter the folder name
        $previous_folder = substr($folder, 0, strrpos($folder, '/'));

        echo('<div class="one-browse previous manager-images"><a href="./?b='.$mode.'&s='.urlencode($previous_folder).$keep_get.'">'.T_("Previous").'</a></div>');
    }

    // Empty or non-existing directory?
    if(!count($scan) || !is_dir($directory)) {
        echo('<div class="one-browse '.$marker.' alert manager-images">'.T_("The folder is empty.").'</div>');

        return false;
    }

    // Echo the browsing HTML code
    foreach($scan as $current) {
        // Generate the item path$directory
        $path = $directory.'/'.$current;
        $file = $folder.'/'.$current;

        if(is_dir($path)) {
            // Directory
            $type = 'folder';
            $href = './?b='.$mode.'&s='.urlencode($file).$keep_get;
            $target = '';
        } else {
            // File
            $type = getFileType(getFileExt($path));
            $href = $path;
            $target = ' target="_blank"';
        }

        echo('<div class="one-browse '.$marker.' '.$type.' manager-images"><a href="'.$href.'"'.$target.'>'.htmlspecialchars($current).'</a><input type="checkbox" name="element_'.md5($file).'" value="'.htmlspecialchars($file).'" /></div>');

        // Change the marker
        if($marker == 'odd') {
            $marker = 'even';
        } else {
            $marker = 'odd';
        }
    }

    return true;
}

// Removes selected elements (files/folders)
function removeElements() {
    // Initialize the match
    $elements_removed = false;
    $elements_remove = array();

    // Try to get the elements to remove
    foreach($_POST as $post_key => $post_value) {
        // Is a safe file?
        if(preg_match('/^element_(.+)$/i', $post_key) && isSafe($post_value)) {
            // Update the marker
            $elements_removed = true;

            // Get the real path
            $post_element = JAPPIX_BASE.'/store/'.$post_value;

            // Remove the current element
            if(is_dir($post_element)) {
                removeDir($post_element);
            } else if(file_exists($post_element)) {
                if(substr($post_value,-4) == '.xml') {
                    $content_file = substr($post_element,0,-4);
                    unlink($content_file);

                    if(file_exists($content_file.'_thumb.jpg')) {
                        unlink($content_file.'_thumb.jpg');
                    }
                }
                unlink($post_element);
            }
        }
    }

    // Show a notification message
    if($elements_removed) {
        echo('<p class="info smallspace success">'.T_("The selected elements have been removed.").'</p>');
    } else {
        echo('<p class="info smallspace fail">'.T_("You must select elements to remove!").'</p>');
    }
}

// Returns users browsing informations
function browseUsers() {
    // Get the users
    $array = getUsers();

    // Odd/even marker
    $marker = 'odd';

    // Echo the browsing HTML code
    foreach($array as $user => $password) {
        // Filter the username
        $user = htmlspecialchars($user);

        // Output the code
        echo('<div class="one-browse '.$marker.' user manager-images"><span>'.$user.'</span><input type="checkbox" name="admin_'.md5($user).'" value="'.$user.'" /><div class="clear"></div></div>');

        // Change the marker
        if($marker == 'odd') {
            $marker = 'even';
        } else {
            $marker = 'odd';
        }
    }
}

// Generates the logo form field
function logoFormField($id, $name) {
    if(file_exists(JAPPIX_BASE.'/store/logos/'.$name.'.png')) {
        echo '<span class="logo_links"><a class="remove manager-images" href="./?k='.urlencode($name).keepGet('k', false).'" title="'.T_("Remove this logo").'"></a><a class="view manager-images" href="./store/logos/'.$name.'.png" target="_blank" title="'.T_("View this logo").'"></a></span>';
    } else {
        echo '<input id="logo_own_'.$id.'_location" type="file" name="logo_own_'.$id.'_location" accept="image/*" />';
    }

    echo "\n";
}

// Reads the background configuration
function readBackground() {
    // Read the background configuration XML
    $background_data = readXML('conf', 'background');

    // Get the default values
    $background_default = defaultBackground();

    // Stored data array
    $background_conf = array();

    // Read the stored values
    if($background_data) {
        // Initialize the background configuration XML data
        $background_xml = new SimpleXMLElement($background_data);

        // Loop the notice configuration elements
        foreach($background_xml->children() as $background_child) {
            $background_conf[$background_child->getName()] = (string)$background_child;
        }
    }

    // Checks no value is missing in the stored configuration
    foreach($background_default as $background_name => $background_value) {
        if(!isset($background_conf[$background_name]) || empty($background_conf[$background_name])) {
            $background_conf[$background_name] = $background_default[$background_name];
        }
    }

    return $background_conf;
}

// Writes the background configuration
function writeBackground($array) {
    // Generate the XML data
    $xml = '';

    foreach($array as $key => $value) {
        $xml .= "\n".'  <'.$key.'>'.stripslashes(htmlspecialchars($value)).'</'.$key.'>';
    }

    // Write this data
    writeXML('conf', 'background', $xml);
}

// Generates a list of the available background images
function getBackgrounds() {
    // Initialize the result array
    $array = array();

    // Scan the background directory
    $scan = scandir(JAPPIX_BASE.'/store/backgrounds/');

    foreach($scan as $current) {
        if(isImage($current)) {
            array_push($array, $current);
        }
    }

    return $array;
}

// Writes the notice configuration
function writeNotice($type, $simple) {
    // Generate the XML data
    $xml =
    '<type>'.$type.'</type>
    <notice>'.stripslashes(htmlspecialchars($simple)).'</notice>'
    ;

    // Write this data
    writeXML('conf', 'notice', $xml);
}

?>