Completed
Push — master ( 369c90...324e29 )
by Michael
04:57
created
class/lite.php 2 patches
Indentation   +836 added lines, -836 removed lines patch added patch discarded remove patch
@@ -28,840 +28,840 @@
 block discarded – undo
28 28
 class references_Cache_Lite
29 29
 {
30 30
 
31
-    // --- Private properties ---
32
-
33
-    /**
34
-     * Directory where to put the cache files
35
-     * (make sure to add a trailing slash)
36
-     *
37
-     * @var string $_cacheDir
38
-     */
39
-    public $_cacheDir = '/tmp/';
40
-
41
-    /**
42
-     * Enable / disable caching
43
-     *
44
-     * (can be very usefull for the debug of cached scripts)
45
-     *
46
-     * @var boolean $_caching
47
-     */
48
-    public $_caching = true;
49
-
50
-    /**
51
-     * Cache lifetime (in seconds)
52
-     *
53
-     * If null, the cache is valid forever.
54
-     *
55
-     * @var int $_lifeTime
56
-     */
57
-    public $_lifeTime = 3600;
58
-
59
-    /**
60
-     * Enable / disable fileLocking
61
-     *
62
-     * (can avoid cache corruption under bad circumstances)
63
-     *
64
-     * @var boolean $_fileLocking
65
-     */
66
-    public $_fileLocking = true;
67
-
68
-    /**
69
-     * Timestamp of the last valid cache
70
-     *
71
-     * @var int $_refreshTime
72
-     */
73
-    public $_refreshTime;
74
-
75
-    /**
76
-     * File name (with path)
77
-     *
78
-     * @var string $_file
79
-     */
80
-    public $_file;
81
-
82
-    /**
83
-     * File name (without path)
84
-     *
85
-     * @var string $_fileName
86
-     */
87
-    public $_fileName;
88
-
89
-    /**
90
-     * Enable / disable write control (the cache is read just after writing to detect corrupt entries)
91
-     *
92
-     * Enable write control will lightly slow the cache writing but not the cache reading
93
-     * Write control can detect some corrupt cache files but maybe it's not a perfect control
94
-     *
95
-     * @var boolean $_writeControl
96
-     */
97
-    public $_writeControl = true;
98
-
99
-    /**
100
-     * Enable / disable read control
101
-     *
102
-     * If enabled, a control key is embeded in cache file and this key is compared with the one
103
-     * calculated after the reading.
104
-     *
105
-     * @var boolean $_writeControl
106
-     */
107
-    public $_readControl = true;
108
-
109
-    /**
110
-     * Type of read control (only if read control is enabled)
111
-     *
112
-     * Available values are :
113
-     * 'md5' for a md5 hash control (best but slowest)
114
-     * 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
115
-     * 'strlen' for a length only test (fastest)
116
-     *
117
-     * @var boolean $_readControlType
118
-     */
119
-    public $_readControlType = 'crc32';
120
-
121
-    /**
122
-     * Pear error mode (when raiseError is called)
123
-     *
124
-     * (see PEAR doc)
125
-     *
126
-     * @see setToDebug()
127
-     * @var int $_pearErrorMode
128
-     */
129
-    public $_pearErrorMode = REFERENCES_CACHE_LITE_ERROR_RETURN;
130
-
131
-    /**
132
-     * Current cache id
133
-     *
134
-     * @var string $_id
135
-     */
136
-    public $_id;
137
-
138
-    /**
139
-     * Current cache group
140
-     *
141
-     * @var string $_group
142
-     */
143
-    public $_group;
144
-
145
-    /**
146
-     * Enable / Disable "Memory Caching"
147
-     *
148
-     * NB : There is no lifetime for memory caching !
149
-     *
150
-     * @var boolean $_memoryCaching
151
-     */
152
-    public $_memoryCaching = false;
153
-
154
-    /**
155
-     * Enable / Disable "Only Memory Caching"
156
-     * (be carefull, memory caching is "beta quality")
157
-     *
158
-     * @var boolean $_onlyMemoryCaching
159
-     */
160
-    public $_onlyMemoryCaching = false;
161
-
162
-    /**
163
-     * Memory caching array
164
-     *
165
-     * @var array $_memoryCachingArray
166
-     */
167
-    public $_memoryCachingArray = array();
168
-
169
-    /**
170
-     * Memory caching counter
171
-     *
172
-     * @var int $memoryCachingCounter
173
-     */
174
-    public $_memoryCachingCounter = 0;
175
-
176
-    /**
177
-     * Memory caching limit
178
-     *
179
-     * @var int $memoryCachingLimit
180
-     */
181
-    public $_memoryCachingLimit = 1000;
182
-
183
-    /**
184
-     * File Name protection
185
-     *
186
-     * if set to true, you can use any cache id or group name
187
-     * if set to false, it can be faster but cache ids and group names
188
-     * will be used directly in cache file names so be carefull with
189
-     * special characters...
190
-     *
191
-     * @var boolean $fileNameProtection
192
-     */
193
-    public $_fileNameProtection = true;
194
-
195
-    /**
196
-     * Enable / disable automatic serialization
197
-     *
198
-     * it can be used to save directly datas which aren't strings
199
-     * (but it's slower)
200
-     *
201
-     * @var boolean $_serialize
202
-     */
203
-    public $_automaticSerialization = false;
204
-
205
-    /**
206
-     * Disable / Tune the automatic cleaning process
207
-     *
208
-     * The automatic cleaning process destroy too old (for the given life time)
209
-     * cache files when a new cache file is written.
210
-     * 0               => no automatic cache cleaning
211
-     * 1               => systematic cache cleaning
212
-     * x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
213
-     *
214
-     * @var int $_automaticCleaning
215
-     */
216
-    public $_automaticCleaningFactor = 0;
217
-
218
-    /**
219
-     * Nested directory level
220
-     *
221
-     * Set the hashed directory structure level. 0 means "no hashed directory
222
-     * structure", 1 means "one level of directory", 2 means "two levels"...
223
-     * This option can speed up Cache_Lite only when you have many thousands of
224
-     * cache file. Only specific benchs can help you to choose the perfect value
225
-     * for you. Maybe, 1 or 2 is a good start.
226
-     *
227
-     * @var int $_hashedDirectoryLevel
228
-     */
229
-    public $_hashedDirectoryLevel = 0;
230
-
231
-    /**
232
-     * Umask for hashed directory structure
233
-     *
234
-     * @var int $_hashedDirectoryUmask
235
-     */
236
-    public $_hashedDirectoryUmask = 0700;
237
-
238
-    /**
239
-     * API break for error handling in REFERENCES_CACHE_LITE_ERROR_RETURN mode
240
-     *
241
-     * In REFERENCES_CACHE_LITE_ERROR_RETURN mode, error handling was not good because
242
-     * for example save() method always returned a boolean (a PEAR_Error object
243
-     * would be better in REFERENCES_CACHE_LITE_ERROR_RETURN mode). To correct this without
244
-     * breaking the API, this option (false by default) can change this handling.
245
-     *
246
-     * @var boolean
247
-     */
248
-    public $_errorHandlingAPIBreak = false;
249
-
250
-    // --- Public methods ---
251
-
252
-    /**
253
-     * Constructor
254
-     *
255
-     * $options is an assoc. Available options are :
256
-     * $options = array(
257
-     *     'cacheDir' => directory where to put the cache files (string) ,
258
-     *     'caching' => enable / disable caching (boolean) ,
259
-     *     'lifeTime' => cache lifetime in seconds (int) ,
260
-     *     'fileLocking' => enable / disable fileLocking (boolean) ,
261
-     *     'writeControl' => enable / disable write control (boolean) ,
262
-     *     'readControl' => enable / disable read control (boolean) ,
263
-     *     'readControlType' => type of read control 'crc32', 'md5', 'strlen' (string) ,
264
-     *     'pearErrorMode' => pear error mode (when raiseError is called) (cf PEAR doc) (int) ,
265
-     *     'memoryCaching' => enable / disable memory caching (boolean) ,
266
-     *     'onlyMemoryCaching' => enable / disable only memory caching (boolean) ,
267
-     *     'memoryCachingLimit' => max nbr of records to store into memory caching (int) ,
268
-     *     'fileNameProtection' => enable / disable automatic file name protection (boolean) ,
269
-     *     'automaticSerialization' => enable / disable automatic serialization (boolean) ,
270
-     *     'automaticCleaningFactor' => distable / tune automatic cleaning process (int) ,
271
-     *     'hashedDirectoryLevel' => level of the hashed directory system (int) ,
272
-     *     'hashedDirectoryUmask' => umask for hashed directory structure (int) ,
273
-     *     'errorHandlingAPIBreak' => API break for better error handling ? (boolean)
274
-     * );
275
-     *
276
-     * @param array $options options
277
-     * @access public
278
-     */
279
-    public function __construct($options = array(null))
280
-    {
281
-        foreach ($options as $key => $value) {
282
-            $this->setOption($key, $value);
283
-        }
284
-    }
285
-
286
-    /**
287
-     * Generic way to set a Cache_Lite option
288
-     *
289
-     * see Cache_Lite constructor for available options
290
-     *
291
-     * @var string $name  name of the option
292
-     * @var mixed  $value value of the option
293
-     * @access public
294
-     */
295
-    public function setOption($name, $value)
296
-    {
297
-        $availableOptions = array(
298
-            'errorHandlingAPIBreak',
299
-            'hashedDirectoryUmask',
300
-            'hashedDirectoryLevel',
301
-            'automaticCleaningFactor',
302
-            'automaticSerialization',
303
-            'fileNameProtection',
304
-            'memoryCaching',
305
-            'onlyMemoryCaching',
306
-            'memoryCachingLimit',
307
-            'cacheDir',
308
-            'caching',
309
-            'lifeTime',
310
-            'fileLocking',
311
-            'writeControl',
312
-            'readControl',
313
-            'readControlType',
314
-            'pearErrorMode'
315
-        );
316
-        if (in_array($name, $availableOptions)) {
317
-            $property        = '_' . $name;
318
-            $this->$property = $value;
319
-        }
320
-    }
321
-
322
-    /**
323
-     * Test if a cache is available and (if yes) return it
324
-     *
325
-     * @param string  $id                     cache id
326
-     * @param string  $group                  name of the cache group
327
-     * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
328
-     * @return string data of the cache (else : false)
329
-     * @access public
330
-     */
331
-    public function get($id, $group = 'default', $doNotTestCacheValidity = false)
332
-    {
333
-        $this->_id    = $id;
334
-        $this->_group = $group;
335
-        $data         = false;
336
-        if ($this->_caching) {
337
-            $this->_setRefreshTime();
338
-            $this->_setFileName($id, $group);
339
-            clearstatcache();
340
-            if ($this->_memoryCaching) {
341
-                if (isset($this->_memoryCachingArray[$this->_file])) {
342
-                    if ($this->_automaticSerialization) {
343
-                        return unserialize($this->_memoryCachingArray[$this->_file]);
344
-                    }
345
-
346
-                    return $this->_memoryCachingArray[$this->_file];
347
-                }
348
-                if ($this->_onlyMemoryCaching) {
349
-                    return false;
350
-                }
351
-            }
352
-            if ($doNotTestCacheValidity || is_null($this->_refreshTime)) {
353
-                if (file_exists($this->_file)) {
354
-                    $data = $this->_read();
355
-                }
356
-            } else {
357
-                if (file_exists($this->_file) && (@filemtime($this->_file) > $this->_refreshTime)) {
358
-                    $data = $this->_read();
359
-                }
360
-            }
361
-            if ($data && $this->_memoryCaching) {
362
-                $this->_memoryCacheAdd($data);
363
-            }
364
-            if ($this->_automaticSerialization && is_string($data)) {
365
-                $data = unserialize($data);
366
-            }
367
-
368
-            return $data;
369
-        }
370
-
371
-        return false;
372
-    }
373
-
374
-    /**
375
-     * Save some data in a cache file
376
-     *
377
-     * @param string $data  data to put in cache (can be another type than strings if automaticSerialization is on)
378
-     * @param string $id    cache id
379
-     * @param string $group name of the cache group
380
-     * @return boolean true if no problem (else : false or a PEAR_Error object)
381
-     * @access public
382
-     */
383
-    public function save($data, $id = null, $group = 'default')
384
-    {
385
-        if ($this->_caching) {
386
-            if ($this->_automaticSerialization) {
387
-                $data = serialize($data);
388
-            }
389
-            if (isset($id)) {
390
-                $this->_setFileName($id, $group);
391
-            }
392
-            if ($this->_memoryCaching) {
393
-                $this->_memoryCacheAdd($data);
394
-                if ($this->_onlyMemoryCaching) {
395
-                    return true;
396
-                }
397
-            }
398
-            if ($this->_automaticCleaningFactor > 0 && ($this->_automaticCleaningFactor == 1 || mt_rand(1, $this->_automaticCleaningFactor) == 1)) {
399
-                $this->clean(false, 'old');
400
-            }
401
-            if ($this->_writeControl) {
402
-                $res = $this->_writeAndControl($data);
403
-                if (is_bool($res)) {
404
-                    if ($res) {
405
-                        return true;
406
-                    }
407
-                    // if $res if false, we need to invalidate the cache
408
-                    @touch($this->_file, time() - 2 * abs($this->_lifeTime));
409
-
410
-                    return false;
411
-                }
412
-            } else {
413
-                $res = $this->_write($data);
414
-            }
415
-            if (is_object($res)) {
416
-                // $res is a PEAR_Error object
417
-                if (!$this->_errorHandlingAPIBreak) {
418
-                    return false; // we return false (old API)
419
-                }
420
-            }
421
-
422
-            return $res;
423
-        }
424
-
425
-        return false;
426
-    }
427
-
428
-    /**
429
-     * Remove a cache file
430
-     *
431
-     * @param string  $id                cache id
432
-     * @param string  $group             name of the cache group
433
-     * @param boolean $checkbeforeunlink check if file exists before removing it
434
-     * @return boolean true if no problem
435
-     * @access public
436
-     */
437
-    public function remove($id, $group = 'default', $checkbeforeunlink = false)
438
-    {
439
-        $this->_setFileName($id, $group);
440
-        if ($this->_memoryCaching) {
441
-            if (isset($this->_memoryCachingArray[$this->_file])) {
442
-                unset($this->_memoryCachingArray[$this->_file]);
443
-                --$this->_memoryCachingCounter;
444
-            }
445
-            if ($this->_onlyMemoryCaching) {
446
-                return true;
447
-            }
448
-        }
449
-        if ($checkbeforeunlink) {
450
-            if (!file_exists($this->_file)) {
451
-                return true;
452
-            }
453
-        }
454
-
455
-        return $this->_unlink($this->_file);
456
-    }
457
-
458
-    /**
459
-     * Clean the cache
460
-     *
461
-     * if no group is specified all cache files will be destroyed
462
-     * else only cache files of the specified group will be destroyed
463
-     *
464
-     * @param bool|string $group              name of the cache group
465
-     * @param string      $mode               flush cache mode : 'old', 'ingroup', 'notingroup',
466
-     *                                        'callback_myFunction'
467
-     * @return bool true if no problem
468
-     * @access public
469
-     */
470
-    public function clean($group = false, $mode = 'ingroup')
471
-    {
472
-        return $this->_cleanDir($this->_cacheDir, $group, $mode);
473
-    }
474
-
475
-    /**
476
-     * Set to debug mode
477
-     *
478
-     * When an error is found, the script will stop and the message will be displayed
479
-     * (in debug mode only).
480
-     *
481
-     * @access public
482
-     */
483
-    public function setToDebug()
484
-    {
485
-        $this->setOption('pearErrorMode', REFERENCES_CACHE_LITE_ERROR_DIE);
486
-    }
487
-
488
-    /**
489
-     * Set a new life time
490
-     *
491
-     * @param int $newLifeTime new life time (in seconds)
492
-     * @access public
493
-     */
494
-    public function setLifeTime($newLifeTime)
495
-    {
496
-        $this->_lifeTime = $newLifeTime;
497
-        $this->_setRefreshTime();
498
-    }
499
-
500
-    /**
501
-     * Save the state of the caching memory array into a cache file cache
502
-     *
503
-     * @param string $id    cache id
504
-     * @param string $group name of the cache group
505
-     * @access public
506
-     */
507
-    public function saveMemoryCachingState($id, $group = 'default')
508
-    {
509
-        if ($this->_caching) {
510
-            $array = array(
511
-                'counter' => $this->_memoryCachingCounter,
512
-                'array'   => $this->_memoryCachingArray
513
-            );
514
-            $data  = serialize($array);
515
-            $this->save($data, $id, $group);
516
-        }
517
-    }
518
-
519
-    /**
520
-     * Load the state of the caching memory array from a given cache file cache
521
-     *
522
-     * @param string  $id                     cache id
523
-     * @param string  $group                  name of the cache group
524
-     * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
525
-     * @access public
526
-     */
527
-    public function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
528
-    {
529
-        if ($this->_caching) {
530
-            if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
531
-                $array                       = unserialize($data);
532
-                $this->_memoryCachingCounter = $array['counter'];
533
-                $this->_memoryCachingArray   = $array['array'];
534
-            }
535
-        }
536
-    }
537
-
538
-    /**
539
-     * Return the cache last modification time
540
-     *
541
-     * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
542
-     *
543
-     * @return int last modification time
544
-     */
545
-    public function lastModified()
546
-    {
547
-        return @filemtime($this->_file);
548
-    }
549
-
550
-    /**
551
-     * Trigger a PEAR error
552
-     *
553
-     * To improve performances, the PEAR.php file is included dynamically.
554
-     * The file is so included only when an error is triggered. So, in most
555
-     * cases, the file isn't included and perfs are much better.
556
-     *
557
-     * @param string $msg  error message
558
-     * @param int    $code error code
559
-     * @access public
560
-     * @return object
561
-     */
562
-    public function raiseError($msg, $code)
563
-    {
564
-        include_once('PEAR.php');
565
-
566
-        return references_PEAR::raiseError($msg, $code, $this->_pearErrorMode);
567
-    }
568
-
569
-    /**
570
-     * Extend the life of a valid cache file
571
-     *
572
-     * see http://pear.php.net/bugs/bug.php?id=6681
573
-     *
574
-     * @access public
575
-     */
576
-    public function extendLife()
577
-    {
578
-        @touch($this->_file);
579
-    }
580
-
581
-    // --- Private methods ---
582
-
583
-    /**
584
-     * Compute & set the refresh time
585
-     *
586
-     * @access private
587
-     */
588
-    public function _setRefreshTime()
589
-    {
590
-        if (is_null($this->_lifeTime)) {
591
-            $this->_refreshTime = null;
592
-        } else {
593
-            $this->_refreshTime = time() - $this->_lifeTime;
594
-        }
595
-    }
596
-
597
-    /**
598
-     * Remove a file
599
-     *
600
-     * @param string $file complete file path and name
601
-     * @return boolean true if no problem
602
-     * @access private
603
-     */
604
-    public function _unlink($file)
605
-    {
606
-        if (!@unlink($file)) {
607
-            return $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
608
-        }
609
-
610
-        return true;
611
-    }
612
-
613
-    /**
614
-     * Recursive function for cleaning cache file in the given directory
615
-     *
616
-     * @param string      $dir   directory complete path (with a trailing slash)
617
-     * @param bool|string $group name of the cache group
618
-     * @param string      $mode  flush cache mode : 'old', 'ingroup', 'notingroup',
619
-     *                           'callback_myFunction'
620
-     * @return bool true if no problem
621
-     * @access private
622
-     */
623
-    public function _cleanDir($dir, $group = false, $mode = 'ingroup')
624
-    {
625
-        if ($this->_fileNameProtection) {
626
-            $motif = $group ? 'cache_' . md5($group) . '_' : 'cache_';
627
-        } else {
628
-            $motif = $group ? 'cache_' . $group . '_' : 'cache_';
629
-        }
630
-        if ($this->_memoryCaching) {
631
-            foreach ($this->_memoryCachingArray as $key => $v) {
632
-                if (strpos($key, $motif) !== false) {
633
-                    unset($this->_memoryCachingArray[$key]);
634
-                    --$this->_memoryCachingCounter;
635
-                }
636
-            }
637
-            if ($this->_onlyMemoryCaching) {
638
-                return true;
639
-            }
640
-        }
641
-        if (!($dh = opendir($dir))) {
642
-            return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
643
-        }
644
-        $result = true;
645
-        while ($file = readdir($dh)) {
646
-            if (($file !== '.') && ($file !== '..')) {
647
-                if (substr($file, 0, 6) === 'cache_') {
648
-                    $file2 = $dir . $file;
649
-                    if (is_file($file2)) {
650
-                        switch (substr($mode, 0, 9)) {
651
-                            case 'old':
652
-                                // files older than lifeTime get deleted from cache
653
-                                if (!is_null($this->_lifeTime)) {
654
-                                    if ((time() - @filemtime($file2)) > $this->_lifeTime) {
655
-                                        $result = ($result and $this->_unlink($file2));
656
-                                    }
657
-                                }
658
-                                break;
659
-                            case 'notingrou':
660
-                                if (strpos($file2, $motif) === false) {
661
-                                    $result = ($result and $this->_unlink($file2));
662
-                                }
663
-                                break;
664
-                            case 'callback_':
665
-                                $func = substr($mode, 9, strlen($mode) - 9);
666
-                                if ($func($file2, $group)) {
667
-                                    $result = ($result and $this->_unlink($file2));
668
-                                }
669
-                                break;
670
-                            case 'ingroup':
671
-                            default:
672
-                                if (strpos($file2, $motif) !== false) {
673
-                                    $result = ($result and $this->_unlink($file2));
674
-                                }
675
-                                break;
676
-                        }
677
-                    }
678
-                    if (is_dir($file2) and ($this->_hashedDirectoryLevel > 0)) {
679
-                        $result = ($result and $this->_cleanDir($file2 . '/', $group, $mode));
680
-                    }
681
-                }
682
-            }
683
-        }
684
-
685
-        return $result;
686
-    }
687
-
688
-    /**
689
-     * Add some date in the memory caching array
690
-     *
691
-     * @param string $data data to cache
692
-     * @access private
693
-     */
694
-    public function _memoryCacheAdd($data)
695
-    {
696
-        $this->_memoryCachingArray[$this->_file] = $data;
697
-        if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
698
-            list($key,) = each($this->_memoryCachingArray);
699
-            unset($this->_memoryCachingArray[$key]);
700
-        } else {
701
-            ++$this->_memoryCachingCounter;
702
-        }
703
-    }
704
-
705
-    /**
706
-     * Make a file name (with path)
707
-     *
708
-     * @param string $id    cache id
709
-     * @param string $group name of the group
710
-     * @access private
711
-     */
712
-    public function _setFileName($id, $group)
713
-    {
714
-        if ($this->_fileNameProtection) {
715
-            $suffix = 'cache_' . md5($group) . '_' . md5($id);
716
-        } else {
717
-            $suffix = 'cache_' . $group . '_' . $id;
718
-        }
719
-        $root = $this->_cacheDir;
720
-        if ($this->_hashedDirectoryLevel > 0) {
721
-            $hash = md5($suffix);
722
-            for ($i = 0; $i < $this->_hashedDirectoryLevel; ++$i) {
723
-                $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
724
-            }
725
-        }
726
-        $this->_fileName = $suffix;
727
-        $this->_file     = $root . $suffix;
728
-    }
729
-
730
-    /**
731
-     * Read the cache file and return the content
732
-     *
733
-     * @return string content of the cache file (else : false or a PEAR_Error object)
734
-     * @access private
735
-     */
736
-    public function _read()
737
-    {
738
-        $fp = @fopen($this->_file, 'rb');
739
-        if ($this->_fileLocking) {
740
-            @flock($fp, LOCK_SH);
741
-        }
742
-        if ($fp) {
743
-            clearstatcache();
744
-            $length = @filesize($this->_file);
745
-            //            $mqr = get_magic_quotes_runtime();
746
-            //            @set_magic_quotes_runtime(0);
747
-            if ($this->_readControl) {
748
-                $hashControl = @fread($fp, 32);
749
-                $length      = $length - 32;
750
-            }
751
-            if ($length) {
752
-                $data = @fread($fp, $length);
753
-            } else {
754
-                $data = '';
755
-            }
756
-            //            @set_magic_quotes_runtime($mqr);
757
-            if ($this->_fileLocking) {
758
-                @flock($fp, LOCK_UN);
759
-            }
760
-            @fclose($fp);
761
-            if ($this->_readControl) {
762
-                $hashData = $this->_hash($data, $this->_readControlType);
763
-                if ($hashData != $hashControl) {
764
-                    if (!is_null($this->_lifeTime)) {
765
-                        @touch($this->_file, time() - 2 * abs($this->_lifeTime));
766
-                    } else {
767
-                        @unlink($this->_file);
768
-                    }
769
-
770
-                    return false;
771
-                }
772
-            }
773
-
774
-            return $data;
775
-        }
776
-
777
-        return $this->raiseError('Cache_Lite : Unable to read cache !', -2);
778
-    }
779
-
780
-    /**
781
-     * Write the given data in the cache file
782
-     *
783
-     * @param string $data data to put in cache
784
-     * @return boolean true if ok (a PEAR_Error object else)
785
-     * @access private
786
-     */
787
-    public function _write($data)
788
-    {
789
-        if ($this->_hashedDirectoryLevel > 0) {
790
-            $hash = md5($this->_fileName);
791
-            $root = $this->_cacheDir;
792
-            for ($i = 0; $i < $this->_hashedDirectoryLevel; ++$i) {
793
-                $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
794
-                if (!(@is_dir($root))) {
795
-                    @mkdir($root, $this->_hashedDirectoryUmask);
796
-                }
797
-            }
798
-        }
799
-        $fp = @fopen($this->_file, 'wb');
800
-        if ($fp) {
801
-            if ($this->_fileLocking) {
802
-                @flock($fp, LOCK_EX);
803
-            }
804
-            if ($this->_readControl) {
805
-                @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
806
-            }
807
-            //            $mqr = get_magic_quotes_runtime();
808
-            //            @set_magic_quotes_runtime(0);
809
-            @fwrite($fp, $data);
810
-            //            @set_magic_quotes_runtime($mqr);
811
-            if ($this->_fileLocking) {
812
-                @flock($fp, LOCK_UN);
813
-            }
814
-            @fclose($fp);
815
-
816
-            return true;
817
-        }
818
-
819
-        return $this->raiseError('Cache_Lite : Unable to write cache file : ' . $this->_file, -1);
820
-    }
821
-
822
-    /**
823
-     * Write the given data in the cache file and control it just after to avoir corrupted cache entries
824
-     *
825
-     * @param string $data data to put in cache
826
-     * @return boolean true if the test is ok (else : false or a PEAR_Error object)
827
-     * @access private
828
-     */
829
-    public function _writeAndControl($data)
830
-    {
831
-        $result = $this->_write($data);
832
-        if (is_object($result)) {
833
-            return $result; # We return the PEAR_Error object
834
-        }
835
-        $dataRead = $this->_read();
836
-        if (is_object($dataRead)) {
837
-            return $dataRead; # We return the PEAR_Error object
838
-        }
839
-        if (is_bool($dataRead) && (!$dataRead)) {
840
-            return false;
841
-        }
842
-
843
-        return ($dataRead == $data);
844
-    }
845
-
846
-    /**
847
-     * Make a control key with the string containing datas
848
-     *
849
-     * @param string $data        data
850
-     * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
851
-     * @return string control key
852
-     * @access private
853
-     */
854
-    public function _hash($data, $controlType)
855
-    {
856
-        switch ($controlType) {
857
-            case 'md5':
858
-                return md5($data);
859
-            case 'crc32':
860
-                return sprintf('% 32d', crc32($data));
861
-            case 'strlen':
862
-                return sprintf('% 32d', strlen($data));
863
-            default:
864
-                return $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
865
-        }
866
-    }
31
+	// --- Private properties ---
32
+
33
+	/**
34
+	 * Directory where to put the cache files
35
+	 * (make sure to add a trailing slash)
36
+	 *
37
+	 * @var string $_cacheDir
38
+	 */
39
+	public $_cacheDir = '/tmp/';
40
+
41
+	/**
42
+	 * Enable / disable caching
43
+	 *
44
+	 * (can be very usefull for the debug of cached scripts)
45
+	 *
46
+	 * @var boolean $_caching
47
+	 */
48
+	public $_caching = true;
49
+
50
+	/**
51
+	 * Cache lifetime (in seconds)
52
+	 *
53
+	 * If null, the cache is valid forever.
54
+	 *
55
+	 * @var int $_lifeTime
56
+	 */
57
+	public $_lifeTime = 3600;
58
+
59
+	/**
60
+	 * Enable / disable fileLocking
61
+	 *
62
+	 * (can avoid cache corruption under bad circumstances)
63
+	 *
64
+	 * @var boolean $_fileLocking
65
+	 */
66
+	public $_fileLocking = true;
67
+
68
+	/**
69
+	 * Timestamp of the last valid cache
70
+	 *
71
+	 * @var int $_refreshTime
72
+	 */
73
+	public $_refreshTime;
74
+
75
+	/**
76
+	 * File name (with path)
77
+	 *
78
+	 * @var string $_file
79
+	 */
80
+	public $_file;
81
+
82
+	/**
83
+	 * File name (without path)
84
+	 *
85
+	 * @var string $_fileName
86
+	 */
87
+	public $_fileName;
88
+
89
+	/**
90
+	 * Enable / disable write control (the cache is read just after writing to detect corrupt entries)
91
+	 *
92
+	 * Enable write control will lightly slow the cache writing but not the cache reading
93
+	 * Write control can detect some corrupt cache files but maybe it's not a perfect control
94
+	 *
95
+	 * @var boolean $_writeControl
96
+	 */
97
+	public $_writeControl = true;
98
+
99
+	/**
100
+	 * Enable / disable read control
101
+	 *
102
+	 * If enabled, a control key is embeded in cache file and this key is compared with the one
103
+	 * calculated after the reading.
104
+	 *
105
+	 * @var boolean $_writeControl
106
+	 */
107
+	public $_readControl = true;
108
+
109
+	/**
110
+	 * Type of read control (only if read control is enabled)
111
+	 *
112
+	 * Available values are :
113
+	 * 'md5' for a md5 hash control (best but slowest)
114
+	 * 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
115
+	 * 'strlen' for a length only test (fastest)
116
+	 *
117
+	 * @var boolean $_readControlType
118
+	 */
119
+	public $_readControlType = 'crc32';
120
+
121
+	/**
122
+	 * Pear error mode (when raiseError is called)
123
+	 *
124
+	 * (see PEAR doc)
125
+	 *
126
+	 * @see setToDebug()
127
+	 * @var int $_pearErrorMode
128
+	 */
129
+	public $_pearErrorMode = REFERENCES_CACHE_LITE_ERROR_RETURN;
130
+
131
+	/**
132
+	 * Current cache id
133
+	 *
134
+	 * @var string $_id
135
+	 */
136
+	public $_id;
137
+
138
+	/**
139
+	 * Current cache group
140
+	 *
141
+	 * @var string $_group
142
+	 */
143
+	public $_group;
144
+
145
+	/**
146
+	 * Enable / Disable "Memory Caching"
147
+	 *
148
+	 * NB : There is no lifetime for memory caching !
149
+	 *
150
+	 * @var boolean $_memoryCaching
151
+	 */
152
+	public $_memoryCaching = false;
153
+
154
+	/**
155
+	 * Enable / Disable "Only Memory Caching"
156
+	 * (be carefull, memory caching is "beta quality")
157
+	 *
158
+	 * @var boolean $_onlyMemoryCaching
159
+	 */
160
+	public $_onlyMemoryCaching = false;
161
+
162
+	/**
163
+	 * Memory caching array
164
+	 *
165
+	 * @var array $_memoryCachingArray
166
+	 */
167
+	public $_memoryCachingArray = array();
168
+
169
+	/**
170
+	 * Memory caching counter
171
+	 *
172
+	 * @var int $memoryCachingCounter
173
+	 */
174
+	public $_memoryCachingCounter = 0;
175
+
176
+	/**
177
+	 * Memory caching limit
178
+	 *
179
+	 * @var int $memoryCachingLimit
180
+	 */
181
+	public $_memoryCachingLimit = 1000;
182
+
183
+	/**
184
+	 * File Name protection
185
+	 *
186
+	 * if set to true, you can use any cache id or group name
187
+	 * if set to false, it can be faster but cache ids and group names
188
+	 * will be used directly in cache file names so be carefull with
189
+	 * special characters...
190
+	 *
191
+	 * @var boolean $fileNameProtection
192
+	 */
193
+	public $_fileNameProtection = true;
194
+
195
+	/**
196
+	 * Enable / disable automatic serialization
197
+	 *
198
+	 * it can be used to save directly datas which aren't strings
199
+	 * (but it's slower)
200
+	 *
201
+	 * @var boolean $_serialize
202
+	 */
203
+	public $_automaticSerialization = false;
204
+
205
+	/**
206
+	 * Disable / Tune the automatic cleaning process
207
+	 *
208
+	 * The automatic cleaning process destroy too old (for the given life time)
209
+	 * cache files when a new cache file is written.
210
+	 * 0               => no automatic cache cleaning
211
+	 * 1               => systematic cache cleaning
212
+	 * x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
213
+	 *
214
+	 * @var int $_automaticCleaning
215
+	 */
216
+	public $_automaticCleaningFactor = 0;
217
+
218
+	/**
219
+	 * Nested directory level
220
+	 *
221
+	 * Set the hashed directory structure level. 0 means "no hashed directory
222
+	 * structure", 1 means "one level of directory", 2 means "two levels"...
223
+	 * This option can speed up Cache_Lite only when you have many thousands of
224
+	 * cache file. Only specific benchs can help you to choose the perfect value
225
+	 * for you. Maybe, 1 or 2 is a good start.
226
+	 *
227
+	 * @var int $_hashedDirectoryLevel
228
+	 */
229
+	public $_hashedDirectoryLevel = 0;
230
+
231
+	/**
232
+	 * Umask for hashed directory structure
233
+	 *
234
+	 * @var int $_hashedDirectoryUmask
235
+	 */
236
+	public $_hashedDirectoryUmask = 0700;
237
+
238
+	/**
239
+	 * API break for error handling in REFERENCES_CACHE_LITE_ERROR_RETURN mode
240
+	 *
241
+	 * In REFERENCES_CACHE_LITE_ERROR_RETURN mode, error handling was not good because
242
+	 * for example save() method always returned a boolean (a PEAR_Error object
243
+	 * would be better in REFERENCES_CACHE_LITE_ERROR_RETURN mode). To correct this without
244
+	 * breaking the API, this option (false by default) can change this handling.
245
+	 *
246
+	 * @var boolean
247
+	 */
248
+	public $_errorHandlingAPIBreak = false;
249
+
250
+	// --- Public methods ---
251
+
252
+	/**
253
+	 * Constructor
254
+	 *
255
+	 * $options is an assoc. Available options are :
256
+	 * $options = array(
257
+	 *     'cacheDir' => directory where to put the cache files (string) ,
258
+	 *     'caching' => enable / disable caching (boolean) ,
259
+	 *     'lifeTime' => cache lifetime in seconds (int) ,
260
+	 *     'fileLocking' => enable / disable fileLocking (boolean) ,
261
+	 *     'writeControl' => enable / disable write control (boolean) ,
262
+	 *     'readControl' => enable / disable read control (boolean) ,
263
+	 *     'readControlType' => type of read control 'crc32', 'md5', 'strlen' (string) ,
264
+	 *     'pearErrorMode' => pear error mode (when raiseError is called) (cf PEAR doc) (int) ,
265
+	 *     'memoryCaching' => enable / disable memory caching (boolean) ,
266
+	 *     'onlyMemoryCaching' => enable / disable only memory caching (boolean) ,
267
+	 *     'memoryCachingLimit' => max nbr of records to store into memory caching (int) ,
268
+	 *     'fileNameProtection' => enable / disable automatic file name protection (boolean) ,
269
+	 *     'automaticSerialization' => enable / disable automatic serialization (boolean) ,
270
+	 *     'automaticCleaningFactor' => distable / tune automatic cleaning process (int) ,
271
+	 *     'hashedDirectoryLevel' => level of the hashed directory system (int) ,
272
+	 *     'hashedDirectoryUmask' => umask for hashed directory structure (int) ,
273
+	 *     'errorHandlingAPIBreak' => API break for better error handling ? (boolean)
274
+	 * );
275
+	 *
276
+	 * @param array $options options
277
+	 * @access public
278
+	 */
279
+	public function __construct($options = array(null))
280
+	{
281
+		foreach ($options as $key => $value) {
282
+			$this->setOption($key, $value);
283
+		}
284
+	}
285
+
286
+	/**
287
+	 * Generic way to set a Cache_Lite option
288
+	 *
289
+	 * see Cache_Lite constructor for available options
290
+	 *
291
+	 * @var string $name  name of the option
292
+	 * @var mixed  $value value of the option
293
+	 * @access public
294
+	 */
295
+	public function setOption($name, $value)
296
+	{
297
+		$availableOptions = array(
298
+			'errorHandlingAPIBreak',
299
+			'hashedDirectoryUmask',
300
+			'hashedDirectoryLevel',
301
+			'automaticCleaningFactor',
302
+			'automaticSerialization',
303
+			'fileNameProtection',
304
+			'memoryCaching',
305
+			'onlyMemoryCaching',
306
+			'memoryCachingLimit',
307
+			'cacheDir',
308
+			'caching',
309
+			'lifeTime',
310
+			'fileLocking',
311
+			'writeControl',
312
+			'readControl',
313
+			'readControlType',
314
+			'pearErrorMode'
315
+		);
316
+		if (in_array($name, $availableOptions)) {
317
+			$property        = '_' . $name;
318
+			$this->$property = $value;
319
+		}
320
+	}
321
+
322
+	/**
323
+	 * Test if a cache is available and (if yes) return it
324
+	 *
325
+	 * @param string  $id                     cache id
326
+	 * @param string  $group                  name of the cache group
327
+	 * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
328
+	 * @return string data of the cache (else : false)
329
+	 * @access public
330
+	 */
331
+	public function get($id, $group = 'default', $doNotTestCacheValidity = false)
332
+	{
333
+		$this->_id    = $id;
334
+		$this->_group = $group;
335
+		$data         = false;
336
+		if ($this->_caching) {
337
+			$this->_setRefreshTime();
338
+			$this->_setFileName($id, $group);
339
+			clearstatcache();
340
+			if ($this->_memoryCaching) {
341
+				if (isset($this->_memoryCachingArray[$this->_file])) {
342
+					if ($this->_automaticSerialization) {
343
+						return unserialize($this->_memoryCachingArray[$this->_file]);
344
+					}
345
+
346
+					return $this->_memoryCachingArray[$this->_file];
347
+				}
348
+				if ($this->_onlyMemoryCaching) {
349
+					return false;
350
+				}
351
+			}
352
+			if ($doNotTestCacheValidity || is_null($this->_refreshTime)) {
353
+				if (file_exists($this->_file)) {
354
+					$data = $this->_read();
355
+				}
356
+			} else {
357
+				if (file_exists($this->_file) && (@filemtime($this->_file) > $this->_refreshTime)) {
358
+					$data = $this->_read();
359
+				}
360
+			}
361
+			if ($data && $this->_memoryCaching) {
362
+				$this->_memoryCacheAdd($data);
363
+			}
364
+			if ($this->_automaticSerialization && is_string($data)) {
365
+				$data = unserialize($data);
366
+			}
367
+
368
+			return $data;
369
+		}
370
+
371
+		return false;
372
+	}
373
+
374
+	/**
375
+	 * Save some data in a cache file
376
+	 *
377
+	 * @param string $data  data to put in cache (can be another type than strings if automaticSerialization is on)
378
+	 * @param string $id    cache id
379
+	 * @param string $group name of the cache group
380
+	 * @return boolean true if no problem (else : false or a PEAR_Error object)
381
+	 * @access public
382
+	 */
383
+	public function save($data, $id = null, $group = 'default')
384
+	{
385
+		if ($this->_caching) {
386
+			if ($this->_automaticSerialization) {
387
+				$data = serialize($data);
388
+			}
389
+			if (isset($id)) {
390
+				$this->_setFileName($id, $group);
391
+			}
392
+			if ($this->_memoryCaching) {
393
+				$this->_memoryCacheAdd($data);
394
+				if ($this->_onlyMemoryCaching) {
395
+					return true;
396
+				}
397
+			}
398
+			if ($this->_automaticCleaningFactor > 0 && ($this->_automaticCleaningFactor == 1 || mt_rand(1, $this->_automaticCleaningFactor) == 1)) {
399
+				$this->clean(false, 'old');
400
+			}
401
+			if ($this->_writeControl) {
402
+				$res = $this->_writeAndControl($data);
403
+				if (is_bool($res)) {
404
+					if ($res) {
405
+						return true;
406
+					}
407
+					// if $res if false, we need to invalidate the cache
408
+					@touch($this->_file, time() - 2 * abs($this->_lifeTime));
409
+
410
+					return false;
411
+				}
412
+			} else {
413
+				$res = $this->_write($data);
414
+			}
415
+			if (is_object($res)) {
416
+				// $res is a PEAR_Error object
417
+				if (!$this->_errorHandlingAPIBreak) {
418
+					return false; // we return false (old API)
419
+				}
420
+			}
421
+
422
+			return $res;
423
+		}
424
+
425
+		return false;
426
+	}
427
+
428
+	/**
429
+	 * Remove a cache file
430
+	 *
431
+	 * @param string  $id                cache id
432
+	 * @param string  $group             name of the cache group
433
+	 * @param boolean $checkbeforeunlink check if file exists before removing it
434
+	 * @return boolean true if no problem
435
+	 * @access public
436
+	 */
437
+	public function remove($id, $group = 'default', $checkbeforeunlink = false)
438
+	{
439
+		$this->_setFileName($id, $group);
440
+		if ($this->_memoryCaching) {
441
+			if (isset($this->_memoryCachingArray[$this->_file])) {
442
+				unset($this->_memoryCachingArray[$this->_file]);
443
+				--$this->_memoryCachingCounter;
444
+			}
445
+			if ($this->_onlyMemoryCaching) {
446
+				return true;
447
+			}
448
+		}
449
+		if ($checkbeforeunlink) {
450
+			if (!file_exists($this->_file)) {
451
+				return true;
452
+			}
453
+		}
454
+
455
+		return $this->_unlink($this->_file);
456
+	}
457
+
458
+	/**
459
+	 * Clean the cache
460
+	 *
461
+	 * if no group is specified all cache files will be destroyed
462
+	 * else only cache files of the specified group will be destroyed
463
+	 *
464
+	 * @param bool|string $group              name of the cache group
465
+	 * @param string      $mode               flush cache mode : 'old', 'ingroup', 'notingroup',
466
+	 *                                        'callback_myFunction'
467
+	 * @return bool true if no problem
468
+	 * @access public
469
+	 */
470
+	public function clean($group = false, $mode = 'ingroup')
471
+	{
472
+		return $this->_cleanDir($this->_cacheDir, $group, $mode);
473
+	}
474
+
475
+	/**
476
+	 * Set to debug mode
477
+	 *
478
+	 * When an error is found, the script will stop and the message will be displayed
479
+	 * (in debug mode only).
480
+	 *
481
+	 * @access public
482
+	 */
483
+	public function setToDebug()
484
+	{
485
+		$this->setOption('pearErrorMode', REFERENCES_CACHE_LITE_ERROR_DIE);
486
+	}
487
+
488
+	/**
489
+	 * Set a new life time
490
+	 *
491
+	 * @param int $newLifeTime new life time (in seconds)
492
+	 * @access public
493
+	 */
494
+	public function setLifeTime($newLifeTime)
495
+	{
496
+		$this->_lifeTime = $newLifeTime;
497
+		$this->_setRefreshTime();
498
+	}
499
+
500
+	/**
501
+	 * Save the state of the caching memory array into a cache file cache
502
+	 *
503
+	 * @param string $id    cache id
504
+	 * @param string $group name of the cache group
505
+	 * @access public
506
+	 */
507
+	public function saveMemoryCachingState($id, $group = 'default')
508
+	{
509
+		if ($this->_caching) {
510
+			$array = array(
511
+				'counter' => $this->_memoryCachingCounter,
512
+				'array'   => $this->_memoryCachingArray
513
+			);
514
+			$data  = serialize($array);
515
+			$this->save($data, $id, $group);
516
+		}
517
+	}
518
+
519
+	/**
520
+	 * Load the state of the caching memory array from a given cache file cache
521
+	 *
522
+	 * @param string  $id                     cache id
523
+	 * @param string  $group                  name of the cache group
524
+	 * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
525
+	 * @access public
526
+	 */
527
+	public function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
528
+	{
529
+		if ($this->_caching) {
530
+			if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
531
+				$array                       = unserialize($data);
532
+				$this->_memoryCachingCounter = $array['counter'];
533
+				$this->_memoryCachingArray   = $array['array'];
534
+			}
535
+		}
536
+	}
537
+
538
+	/**
539
+	 * Return the cache last modification time
540
+	 *
541
+	 * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
542
+	 *
543
+	 * @return int last modification time
544
+	 */
545
+	public function lastModified()
546
+	{
547
+		return @filemtime($this->_file);
548
+	}
549
+
550
+	/**
551
+	 * Trigger a PEAR error
552
+	 *
553
+	 * To improve performances, the PEAR.php file is included dynamically.
554
+	 * The file is so included only when an error is triggered. So, in most
555
+	 * cases, the file isn't included and perfs are much better.
556
+	 *
557
+	 * @param string $msg  error message
558
+	 * @param int    $code error code
559
+	 * @access public
560
+	 * @return object
561
+	 */
562
+	public function raiseError($msg, $code)
563
+	{
564
+		include_once('PEAR.php');
565
+
566
+		return references_PEAR::raiseError($msg, $code, $this->_pearErrorMode);
567
+	}
568
+
569
+	/**
570
+	 * Extend the life of a valid cache file
571
+	 *
572
+	 * see http://pear.php.net/bugs/bug.php?id=6681
573
+	 *
574
+	 * @access public
575
+	 */
576
+	public function extendLife()
577
+	{
578
+		@touch($this->_file);
579
+	}
580
+
581
+	// --- Private methods ---
582
+
583
+	/**
584
+	 * Compute & set the refresh time
585
+	 *
586
+	 * @access private
587
+	 */
588
+	public function _setRefreshTime()
589
+	{
590
+		if (is_null($this->_lifeTime)) {
591
+			$this->_refreshTime = null;
592
+		} else {
593
+			$this->_refreshTime = time() - $this->_lifeTime;
594
+		}
595
+	}
596
+
597
+	/**
598
+	 * Remove a file
599
+	 *
600
+	 * @param string $file complete file path and name
601
+	 * @return boolean true if no problem
602
+	 * @access private
603
+	 */
604
+	public function _unlink($file)
605
+	{
606
+		if (!@unlink($file)) {
607
+			return $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
608
+		}
609
+
610
+		return true;
611
+	}
612
+
613
+	/**
614
+	 * Recursive function for cleaning cache file in the given directory
615
+	 *
616
+	 * @param string      $dir   directory complete path (with a trailing slash)
617
+	 * @param bool|string $group name of the cache group
618
+	 * @param string      $mode  flush cache mode : 'old', 'ingroup', 'notingroup',
619
+	 *                           'callback_myFunction'
620
+	 * @return bool true if no problem
621
+	 * @access private
622
+	 */
623
+	public function _cleanDir($dir, $group = false, $mode = 'ingroup')
624
+	{
625
+		if ($this->_fileNameProtection) {
626
+			$motif = $group ? 'cache_' . md5($group) . '_' : 'cache_';
627
+		} else {
628
+			$motif = $group ? 'cache_' . $group . '_' : 'cache_';
629
+		}
630
+		if ($this->_memoryCaching) {
631
+			foreach ($this->_memoryCachingArray as $key => $v) {
632
+				if (strpos($key, $motif) !== false) {
633
+					unset($this->_memoryCachingArray[$key]);
634
+					--$this->_memoryCachingCounter;
635
+				}
636
+			}
637
+			if ($this->_onlyMemoryCaching) {
638
+				return true;
639
+			}
640
+		}
641
+		if (!($dh = opendir($dir))) {
642
+			return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
643
+		}
644
+		$result = true;
645
+		while ($file = readdir($dh)) {
646
+			if (($file !== '.') && ($file !== '..')) {
647
+				if (substr($file, 0, 6) === 'cache_') {
648
+					$file2 = $dir . $file;
649
+					if (is_file($file2)) {
650
+						switch (substr($mode, 0, 9)) {
651
+							case 'old':
652
+								// files older than lifeTime get deleted from cache
653
+								if (!is_null($this->_lifeTime)) {
654
+									if ((time() - @filemtime($file2)) > $this->_lifeTime) {
655
+										$result = ($result and $this->_unlink($file2));
656
+									}
657
+								}
658
+								break;
659
+							case 'notingrou':
660
+								if (strpos($file2, $motif) === false) {
661
+									$result = ($result and $this->_unlink($file2));
662
+								}
663
+								break;
664
+							case 'callback_':
665
+								$func = substr($mode, 9, strlen($mode) - 9);
666
+								if ($func($file2, $group)) {
667
+									$result = ($result and $this->_unlink($file2));
668
+								}
669
+								break;
670
+							case 'ingroup':
671
+							default:
672
+								if (strpos($file2, $motif) !== false) {
673
+									$result = ($result and $this->_unlink($file2));
674
+								}
675
+								break;
676
+						}
677
+					}
678
+					if (is_dir($file2) and ($this->_hashedDirectoryLevel > 0)) {
679
+						$result = ($result and $this->_cleanDir($file2 . '/', $group, $mode));
680
+					}
681
+				}
682
+			}
683
+		}
684
+
685
+		return $result;
686
+	}
687
+
688
+	/**
689
+	 * Add some date in the memory caching array
690
+	 *
691
+	 * @param string $data data to cache
692
+	 * @access private
693
+	 */
694
+	public function _memoryCacheAdd($data)
695
+	{
696
+		$this->_memoryCachingArray[$this->_file] = $data;
697
+		if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
698
+			list($key,) = each($this->_memoryCachingArray);
699
+			unset($this->_memoryCachingArray[$key]);
700
+		} else {
701
+			++$this->_memoryCachingCounter;
702
+		}
703
+	}
704
+
705
+	/**
706
+	 * Make a file name (with path)
707
+	 *
708
+	 * @param string $id    cache id
709
+	 * @param string $group name of the group
710
+	 * @access private
711
+	 */
712
+	public function _setFileName($id, $group)
713
+	{
714
+		if ($this->_fileNameProtection) {
715
+			$suffix = 'cache_' . md5($group) . '_' . md5($id);
716
+		} else {
717
+			$suffix = 'cache_' . $group . '_' . $id;
718
+		}
719
+		$root = $this->_cacheDir;
720
+		if ($this->_hashedDirectoryLevel > 0) {
721
+			$hash = md5($suffix);
722
+			for ($i = 0; $i < $this->_hashedDirectoryLevel; ++$i) {
723
+				$root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
724
+			}
725
+		}
726
+		$this->_fileName = $suffix;
727
+		$this->_file     = $root . $suffix;
728
+	}
729
+
730
+	/**
731
+	 * Read the cache file and return the content
732
+	 *
733
+	 * @return string content of the cache file (else : false or a PEAR_Error object)
734
+	 * @access private
735
+	 */
736
+	public function _read()
737
+	{
738
+		$fp = @fopen($this->_file, 'rb');
739
+		if ($this->_fileLocking) {
740
+			@flock($fp, LOCK_SH);
741
+		}
742
+		if ($fp) {
743
+			clearstatcache();
744
+			$length = @filesize($this->_file);
745
+			//            $mqr = get_magic_quotes_runtime();
746
+			//            @set_magic_quotes_runtime(0);
747
+			if ($this->_readControl) {
748
+				$hashControl = @fread($fp, 32);
749
+				$length      = $length - 32;
750
+			}
751
+			if ($length) {
752
+				$data = @fread($fp, $length);
753
+			} else {
754
+				$data = '';
755
+			}
756
+			//            @set_magic_quotes_runtime($mqr);
757
+			if ($this->_fileLocking) {
758
+				@flock($fp, LOCK_UN);
759
+			}
760
+			@fclose($fp);
761
+			if ($this->_readControl) {
762
+				$hashData = $this->_hash($data, $this->_readControlType);
763
+				if ($hashData != $hashControl) {
764
+					if (!is_null($this->_lifeTime)) {
765
+						@touch($this->_file, time() - 2 * abs($this->_lifeTime));
766
+					} else {
767
+						@unlink($this->_file);
768
+					}
769
+
770
+					return false;
771
+				}
772
+			}
773
+
774
+			return $data;
775
+		}
776
+
777
+		return $this->raiseError('Cache_Lite : Unable to read cache !', -2);
778
+	}
779
+
780
+	/**
781
+	 * Write the given data in the cache file
782
+	 *
783
+	 * @param string $data data to put in cache
784
+	 * @return boolean true if ok (a PEAR_Error object else)
785
+	 * @access private
786
+	 */
787
+	public function _write($data)
788
+	{
789
+		if ($this->_hashedDirectoryLevel > 0) {
790
+			$hash = md5($this->_fileName);
791
+			$root = $this->_cacheDir;
792
+			for ($i = 0; $i < $this->_hashedDirectoryLevel; ++$i) {
793
+				$root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
794
+				if (!(@is_dir($root))) {
795
+					@mkdir($root, $this->_hashedDirectoryUmask);
796
+				}
797
+			}
798
+		}
799
+		$fp = @fopen($this->_file, 'wb');
800
+		if ($fp) {
801
+			if ($this->_fileLocking) {
802
+				@flock($fp, LOCK_EX);
803
+			}
804
+			if ($this->_readControl) {
805
+				@fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
806
+			}
807
+			//            $mqr = get_magic_quotes_runtime();
808
+			//            @set_magic_quotes_runtime(0);
809
+			@fwrite($fp, $data);
810
+			//            @set_magic_quotes_runtime($mqr);
811
+			if ($this->_fileLocking) {
812
+				@flock($fp, LOCK_UN);
813
+			}
814
+			@fclose($fp);
815
+
816
+			return true;
817
+		}
818
+
819
+		return $this->raiseError('Cache_Lite : Unable to write cache file : ' . $this->_file, -1);
820
+	}
821
+
822
+	/**
823
+	 * Write the given data in the cache file and control it just after to avoir corrupted cache entries
824
+	 *
825
+	 * @param string $data data to put in cache
826
+	 * @return boolean true if the test is ok (else : false or a PEAR_Error object)
827
+	 * @access private
828
+	 */
829
+	public function _writeAndControl($data)
830
+	{
831
+		$result = $this->_write($data);
832
+		if (is_object($result)) {
833
+			return $result; # We return the PEAR_Error object
834
+		}
835
+		$dataRead = $this->_read();
836
+		if (is_object($dataRead)) {
837
+			return $dataRead; # We return the PEAR_Error object
838
+		}
839
+		if (is_bool($dataRead) && (!$dataRead)) {
840
+			return false;
841
+		}
842
+
843
+		return ($dataRead == $data);
844
+	}
845
+
846
+	/**
847
+	 * Make a control key with the string containing datas
848
+	 *
849
+	 * @param string $data        data
850
+	 * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
851
+	 * @return string control key
852
+	 * @access private
853
+	 */
854
+	public function _hash($data, $controlType)
855
+	{
856
+		switch ($controlType) {
857
+			case 'md5':
858
+				return md5($data);
859
+			case 'crc32':
860
+				return sprintf('% 32d', crc32($data));
861
+			case 'strlen':
862
+				return sprintf('% 32d', strlen($data));
863
+			default:
864
+				return $this->raiseError('Unknown controlType ! (available values are only \'md5\', \'crc32\', \'strlen\')', -5);
865
+		}
866
+	}
867 867
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
             'pearErrorMode'
315 315
         );
316 316
         if (in_array($name, $availableOptions)) {
317
-            $property        = '_' . $name;
317
+            $property        = '_'.$name;
318 318
             $this->$property = $value;
319 319
         }
320 320
     }
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
                 'counter' => $this->_memoryCachingCounter,
512 512
                 'array'   => $this->_memoryCachingArray
513 513
             );
514
-            $data  = serialize($array);
514
+            $data = serialize($array);
515 515
             $this->save($data, $id, $group);
516 516
         }
517 517
     }
@@ -623,9 +623,9 @@  discard block
 block discarded – undo
623 623
     public function _cleanDir($dir, $group = false, $mode = 'ingroup')
624 624
     {
625 625
         if ($this->_fileNameProtection) {
626
-            $motif = $group ? 'cache_' . md5($group) . '_' : 'cache_';
626
+            $motif = $group ? 'cache_'.md5($group).'_' : 'cache_';
627 627
         } else {
628
-            $motif = $group ? 'cache_' . $group . '_' : 'cache_';
628
+            $motif = $group ? 'cache_'.$group.'_' : 'cache_';
629 629
         }
630 630
         if ($this->_memoryCaching) {
631 631
             foreach ($this->_memoryCachingArray as $key => $v) {
@@ -645,7 +645,7 @@  discard block
 block discarded – undo
645 645
         while ($file = readdir($dh)) {
646 646
             if (($file !== '.') && ($file !== '..')) {
647 647
                 if (substr($file, 0, 6) === 'cache_') {
648
-                    $file2 = $dir . $file;
648
+                    $file2 = $dir.$file;
649 649
                     if (is_file($file2)) {
650 650
                         switch (substr($mode, 0, 9)) {
651 651
                             case 'old':
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
                         }
677 677
                     }
678 678
                     if (is_dir($file2) and ($this->_hashedDirectoryLevel > 0)) {
679
-                        $result = ($result and $this->_cleanDir($file2 . '/', $group, $mode));
679
+                        $result = ($result and $this->_cleanDir($file2.'/', $group, $mode));
680 680
                     }
681 681
                 }
682 682
             }
@@ -712,19 +712,19 @@  discard block
 block discarded – undo
712 712
     public function _setFileName($id, $group)
713 713
     {
714 714
         if ($this->_fileNameProtection) {
715
-            $suffix = 'cache_' . md5($group) . '_' . md5($id);
715
+            $suffix = 'cache_'.md5($group).'_'.md5($id);
716 716
         } else {
717
-            $suffix = 'cache_' . $group . '_' . $id;
717
+            $suffix = 'cache_'.$group.'_'.$id;
718 718
         }
719 719
         $root = $this->_cacheDir;
720 720
         if ($this->_hashedDirectoryLevel > 0) {
721 721
             $hash = md5($suffix);
722 722
             for ($i = 0; $i < $this->_hashedDirectoryLevel; ++$i) {
723
-                $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
723
+                $root = $root.'cache_'.substr($hash, 0, $i + 1).'/';
724 724
             }
725 725
         }
726 726
         $this->_fileName = $suffix;
727
-        $this->_file     = $root . $suffix;
727
+        $this->_file     = $root.$suffix;
728 728
     }
729 729
 
730 730
     /**
@@ -790,7 +790,7 @@  discard block
 block discarded – undo
790 790
             $hash = md5($this->_fileName);
791 791
             $root = $this->_cacheDir;
792 792
             for ($i = 0; $i < $this->_hashedDirectoryLevel; ++$i) {
793
-                $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
793
+                $root = $root.'cache_'.substr($hash, 0, $i + 1).'/';
794 794
                 if (!(@is_dir($root))) {
795 795
                     @mkdir($root, $this->_hashedDirectoryUmask);
796 796
                 }
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
             return true;
817 817
         }
818 818
 
819
-        return $this->raiseError('Cache_Lite : Unable to write cache file : ' . $this->_file, -1);
819
+        return $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1);
820 820
     }
821 821
 
822 822
     /**
Please login to merge, or discard this patch.
class/references_handlers.php 2 patches
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -24,34 +24,34 @@
 block discarded – undo
24 24
  */
25 25
 class references_handler
26 26
 {
27
-    public         $h_references_articles   = null;
28
-    public         $h_references_categories = null;
29
-    private static $instance                = false;
27
+	public         $h_references_articles   = null;
28
+	public         $h_references_categories = null;
29
+	private static $instance                = false;
30 30
 
31
-    /**
32
-     * Singleton
33
-     */
34
-    private function __construct()
35
-    {
36
-        $handlersNames = array('references_articles', 'references_categories');
37
-        foreach ($handlersNames as $handlerName) {
38
-            $internalName        = 'h_' . $handlerName;
39
-            $this->$internalName = xoops_getModuleHandler($handlerName, REFERENCES_DIRNAME);
40
-        }
41
-    }
31
+	/**
32
+	 * Singleton
33
+	 */
34
+	private function __construct()
35
+	{
36
+		$handlersNames = array('references_articles', 'references_categories');
37
+		foreach ($handlersNames as $handlerName) {
38
+			$internalName        = 'h_' . $handlerName;
39
+			$this->$internalName = xoops_getModuleHandler($handlerName, REFERENCES_DIRNAME);
40
+		}
41
+	}
42 42
 
43
-    /**
44
-     * Retourne l'instance unique de la clanss
45
-     *
46
-     * @return object
47
-     */
48
-    public static function getInstance()
49
-    {
50
-        static $instance;
51
-        if (null === $instance) {
52
-            $instance = new static();
53
-        }
43
+	/**
44
+	 * Retourne l'instance unique de la clanss
45
+	 *
46
+	 * @return object
47
+	 */
48
+	public static function getInstance()
49
+	{
50
+		static $instance;
51
+		if (null === $instance) {
52
+			$instance = new static();
53
+		}
54 54
 
55
-        return $instance;
56
-    }
55
+		return $instance;
56
+	}
57 57
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@
 block discarded – undo
35 35
     {
36 36
         $handlersNames = array('references_articles', 'references_categories');
37 37
         foreach ($handlersNames as $handlerName) {
38
-            $internalName        = 'h_' . $handlerName;
38
+            $internalName        = 'h_'.$handlerName;
39 39
             $this->$internalName = xoops_getModuleHandler($handlerName, REFERENCES_DIRNAME);
40 40
         }
41 41
     }
Please login to merge, or discard this patch.
class/references_parameters.php 2 patches
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -30,62 +30,62 @@
 block discarded – undo
30 30
  */
31 31
 class references_parameters extends ArrayObject
32 32
 {
33
-    /**
34
-     * Permet de valoriser un indice de la classe comme si c'était une propriété de la classe
35
-     *
36
-     * @example $enregistrement->nom_du_champ = 'ma chaine'
37
-     *
38
-     * @param string $key   Le nom du champ à traiter
39
-     * @param mixed  $value La valeur à lui attribuer
40
-     * @return object
41
-     */
42
-    public function __set($key, $value)
43
-    {
44
-        parent::offsetSet($key, $value);
33
+	/**
34
+	 * Permet de valoriser un indice de la classe comme si c'était une propriété de la classe
35
+	 *
36
+	 * @example $enregistrement->nom_du_champ = 'ma chaine'
37
+	 *
38
+	 * @param string $key   Le nom du champ à traiter
39
+	 * @param mixed  $value La valeur à lui attribuer
40
+	 * @return object
41
+	 */
42
+	public function __set($key, $value)
43
+	{
44
+		parent::offsetSet($key, $value);
45 45
 
46
-        return $this;
47
-    }
46
+		return $this;
47
+	}
48 48
 
49
-    /**
50
-     * Valorisation d'un indice de la classe en utilisant un appel de fonction basé sur le principe suivant :
51
-     *      $maClasse->setLimit(10);
52
-     * Il est possible de chainer comme ceci : $maClasse->setStart(0)->setLimit(10);
53
-     *
54
-     * @param  string $method
55
-     * @param  mixed  $args
56
-     * @return object
57
-     */
58
-    public function __call($method, $args)
59
-    {
60
-        if (substr($method, 0, 3) === 'set') {
61
-            parent::offsetSet(strtolower(substr($method, 3, 1)) . substr($method, 4), $args[0]);
49
+	/**
50
+	 * Valorisation d'un indice de la classe en utilisant un appel de fonction basé sur le principe suivant :
51
+	 *      $maClasse->setLimit(10);
52
+	 * Il est possible de chainer comme ceci : $maClasse->setStart(0)->setLimit(10);
53
+	 *
54
+	 * @param  string $method
55
+	 * @param  mixed  $args
56
+	 * @return object
57
+	 */
58
+	public function __call($method, $args)
59
+	{
60
+		if (substr($method, 0, 3) === 'set') {
61
+			parent::offsetSet(strtolower(substr($method, 3, 1)) . substr($method, 4), $args[0]);
62 62
 
63
-            return $this;
64
-        } else {    // Affichage de la valeur
63
+			return $this;
64
+		} else {    // Affichage de la valeur
65 65
 
66
-            return parent::offsetGet($method);
67
-        }
68
-    }
66
+			return parent::offsetGet($method);
67
+		}
68
+	}
69 69
 
70
-    /**
71
-     * Méthode qui essaye de faire la même chose que la méthode extend() de jQuery
72
-     *
73
-     * On lui passe les valeurs par défaut que l'on attend et la méthode les compare avec les valeurs actuelles
74
-     * Si des valeurs manquent, elles sont ajoutées
75
-     *
76
-     * @param  references_parameters $defaultValues
77
-     * @return references_parameters
78
-     */
79
-    public function extend(self $defaultValues)
80
-    {
81
-        $result = new self;
82
-        $result = $this;
83
-        foreach ($defaultValues as $key => $value) {
84
-            if (!isset($result[$key])) {
85
-                $result[$key] = $value;
86
-            }
87
-        }
70
+	/**
71
+	 * Méthode qui essaye de faire la même chose que la méthode extend() de jQuery
72
+	 *
73
+	 * On lui passe les valeurs par défaut que l'on attend et la méthode les compare avec les valeurs actuelles
74
+	 * Si des valeurs manquent, elles sont ajoutées
75
+	 *
76
+	 * @param  references_parameters $defaultValues
77
+	 * @return references_parameters
78
+	 */
79
+	public function extend(self $defaultValues)
80
+	{
81
+		$result = new self;
82
+		$result = $this;
83
+		foreach ($defaultValues as $key => $value) {
84
+			if (!isset($result[$key])) {
85
+				$result[$key] = $value;
86
+			}
87
+		}
88 88
 
89
-        return $result;
90
-    }
89
+		return $result;
90
+	}
91 91
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@
 block discarded – undo
58 58
     public function __call($method, $args)
59 59
     {
60 60
         if (substr($method, 0, 3) === 'set') {
61
-            parent::offsetSet(strtolower(substr($method, 3, 1)) . substr($method, 4), $args[0]);
61
+            parent::offsetSet(strtolower(substr($method, 3, 1)).substr($method, 4), $args[0]);
62 62
 
63 63
             return $this;
64 64
         } else {    // Affichage de la valeur
Please login to merge, or discard this patch.
category.php 2 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -34,21 +34,21 @@  discard block
 block discarded – undo
34 34
 
35 35
 $category_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0;
36 36
 if ($category_id == 0) {
37
-    header('Location: index.php', true, 301);
38
-    exit;
39
-    //references_utils::redirect('', 'index.php', 0);
37
+	header('Location: index.php', true, 301);
38
+	exit;
39
+	//references_utils::redirect('', 'index.php', 0);
40 40
 }
41 41
 // Chargement de la catégorie
42 42
 $category = null;
43 43
 $category = $h_references_categories->get($category_id);
44 44
 if (!is_object($category)) {
45
-    references_utils::redirect(_MD_REFERENCES_ERROR2, 'index.php', 4);
45
+	references_utils::redirect(_MD_REFERENCES_ERROR2, 'index.php', 4);
46 46
 }
47 47
 
48 48
 // Vérification des permissions
49 49
 $handlers = references_handler::getInstance();
50 50
 if (!$handlers->h_references_categories->userCanSeeCategory($category)) {
51
-    references_utils::redirect(_NOPERM, 'index.php', 4);
51
+	references_utils::redirect(_NOPERM, 'index.php', 4);
52 52
 }
53 53
 
54 54
 $xoopsTpl->assign('category', $category->toArray());
@@ -64,9 +64,9 @@  discard block
 block discarded – undo
64 64
 $xoTheme->addScript(REFERENCES_JS_URL . 'js/mootools.js');
65 65
 $xoTheme->addScript(REFERENCES_JS_URL . 'js/mootools-1.2-more.js');
66 66
 if (isset($xoopsConfig) && file_exists(REFERENCES_PATH . 'language/' . $xoopsConfig['language'] . '/slimbox.js')) {
67
-    $xoTheme->addScript(REFERENCES_URL . 'language/' . $xoopsConfig['language'] . '/slimbox.js');
67
+	$xoTheme->addScript(REFERENCES_URL . 'language/' . $xoopsConfig['language'] . '/slimbox.js');
68 68
 } else {
69
-    $xoTheme->addScript(REFERENCES_JS_URL . 'js/slimbox.js');
69
+	$xoTheme->addScript(REFERENCES_JS_URL . 'js/slimbox.js');
70 70
 }
71 71
 
72 72
 $categoriesSelect = $h_references_categories->getCategoriesSelect('categoriesSelect', $category->getVar('category_id'));
@@ -78,15 +78,15 @@  discard block
 block discarded – undo
78 78
 $xoopsTpl->assign('thumbsWidth', references_utils::getModuleOption('thumbs_width'));
79 79
 $xoopsTpl->assign('thumbsHeight', references_utils::getModuleOption('thumbs_height'));
80 80
 if ($limit > 0) {
81
-    $items          = array();
82
-    $items          = $h_references_articles->getRecentArticles($start, $limit, references_utils::getModuleOption('sort_field'), references_utils::getModuleOption('sort_order'), true, $category_id);
83
-    $categoryTitle  = $category->getVar('category_title');
84
-    $categoryWeight = $category->getVar('category_weight');
85
-    if (count($items) > 0) {
86
-        foreach ($items as $item) {
87
-            $xoopsTpl->append('articles', $item->toArray());
88
-        }
89
-    }
81
+	$items          = array();
82
+	$items          = $h_references_articles->getRecentArticles($start, $limit, references_utils::getModuleOption('sort_field'), references_utils::getModuleOption('sort_order'), true, $category_id);
83
+	$categoryTitle  = $category->getVar('category_title');
84
+	$categoryWeight = $category->getVar('category_weight');
85
+	if (count($items) > 0) {
86
+		foreach ($items as $item) {
87
+			$xoopsTpl->append('articles', $item->toArray());
88
+		}
89
+	}
90 90
 }
91 91
 $xoopsTpl->assign('isAdmin', references_utils::isAdmin());
92 92
 $title = $category->getVar('category_title', 'n') . ' - ' . $xoopsModule->name();
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -24,15 +24,15 @@  discard block
 block discarded – undo
24 24
  *
25 25
  * @param integer $category_id Le numéro de la catégorie
26 26
  */
27
-require __DIR__ . '/header.php';
27
+require __DIR__.'/header.php';
28 28
 $xoopsOption['template_main'] = 'references_category.tpl';
29
-require XOOPS_ROOT_PATH . '/header.php';
29
+require XOOPS_ROOT_PATH.'/header.php';
30 30
 
31
-$baseurl = REFERENCES_URL . basename(__FILE__);
31
+$baseurl = REFERENCES_URL.basename(__FILE__);
32 32
 $limit   = references_utils::getModuleOption('items_index_page');
33 33
 $start   = $index = 0;
34 34
 
35
-$category_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : 0;
35
+$category_id = isset($_GET['category_id']) ? (int) $_GET['category_id'] : 0;
36 36
 if ($category_id == 0) {
37 37
     header('Location: index.php', true, 301);
38 38
     exit;
@@ -61,18 +61,18 @@  discard block
 block discarded – undo
61 61
 $xoopsTpl->assign('use_rss', references_utils::getModuleOption('use_rss'));
62 62
 
63 63
 // MooTools
64
-$xoTheme->addScript(REFERENCES_JS_URL . 'js/mootools.js');
65
-$xoTheme->addScript(REFERENCES_JS_URL . 'js/mootools-1.2-more.js');
66
-if (isset($xoopsConfig) && file_exists(REFERENCES_PATH . 'language/' . $xoopsConfig['language'] . '/slimbox.js')) {
67
-    $xoTheme->addScript(REFERENCES_URL . 'language/' . $xoopsConfig['language'] . '/slimbox.js');
64
+$xoTheme->addScript(REFERENCES_JS_URL.'js/mootools.js');
65
+$xoTheme->addScript(REFERENCES_JS_URL.'js/mootools-1.2-more.js');
66
+if (isset($xoopsConfig) && file_exists(REFERENCES_PATH.'language/'.$xoopsConfig['language'].'/slimbox.js')) {
67
+    $xoTheme->addScript(REFERENCES_URL.'language/'.$xoopsConfig['language'].'/slimbox.js');
68 68
 } else {
69
-    $xoTheme->addScript(REFERENCES_JS_URL . 'js/slimbox.js');
69
+    $xoTheme->addScript(REFERENCES_JS_URL.'js/slimbox.js');
70 70
 }
71 71
 
72 72
 $categoriesSelect = $h_references_categories->getCategoriesSelect('categoriesSelect', $category->getVar('category_id'));
73 73
 $xoopsTpl->assign('categoriesSelect', $categoriesSelect);
74
-$xoTheme->addStylesheet(REFERENCES_JS_URL . 'css/slimbox.css');
75
-$xoTheme->addStylesheet(REFERENCES_JS_URL . 'css/accordion.css');
74
+$xoTheme->addStylesheet(REFERENCES_JS_URL.'css/slimbox.css');
75
+$xoTheme->addStylesheet(REFERENCES_JS_URL.'css/accordion.css');
76 76
 
77 77
 // ****************************************************************************************************************************
78 78
 $xoopsTpl->assign('thumbsWidth', references_utils::getModuleOption('thumbs_width'));
@@ -89,6 +89,6 @@  discard block
 block discarded – undo
89 89
     }
90 90
 }
91 91
 $xoopsTpl->assign('isAdmin', references_utils::isAdmin());
92
-$title = $category->getVar('category_title', 'n') . ' - ' . $xoopsModule->name();
92
+$title = $category->getVar('category_title', 'n').' - '.$xoopsModule->name();
93 93
 references_utils::setMetas($title, $title);
94
-require XOOPS_ROOT_PATH . '/footer.php';
94
+require XOOPS_ROOT_PATH.'/footer.php';
Please login to merge, or discard this patch.
list.tag.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -18,5 +18,5 @@
 block discarded – undo
18 18
  *
19 19
  * ****************************************************************************
20 20
  */
21
-require __DIR__ . '/header.php';
22
-require XOOPS_ROOT_PATH . '/modules/tag/list.tag.php';
21
+require __DIR__.'/header.php';
22
+require XOOPS_ROOT_PATH.'/modules/tag/list.tag.php';
Please login to merge, or discard this patch.
config.php 2 patches
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -19,27 +19,27 @@
 block discarded – undo
19 19
  * ****************************************************************************
20 20
  */
21 21
 if (!defined('REFERENCES_CACHE_PATH')) {
22
-    // Le chemin du cache (il est conseillé de le mettre en dehors de la portée du web)
23
-    define('REFERENCES_CACHE_PATH', XOOPS_UPLOAD_PATH . DIRECTORY_SEPARATOR . REFERENCES_DIRNAME . '_cache' . DIRECTORY_SEPARATOR);
22
+	// Le chemin du cache (il est conseillé de le mettre en dehors de la portée du web)
23
+	define('REFERENCES_CACHE_PATH', XOOPS_UPLOAD_PATH . DIRECTORY_SEPARATOR . REFERENCES_DIRNAME . '_cache' . DIRECTORY_SEPARATOR);
24 24
 
25
-    // Thumbs / Vignettes prefixe
26
-    define('REFERENCES_THUMBS_PREFIX', 'thumb_');        // Thumbs prefix (when thumbs are automatically created)
25
+	// Thumbs / Vignettes prefixe
26
+	define('REFERENCES_THUMBS_PREFIX', 'thumb_');        // Thumbs prefix (when thumbs are automatically created)
27 27
 
28
-    // Short text length / Longueur des textes raccourcis
29
-    define('REFERENCES_SHORTEN_TEXT', '200');        // Characters count / Nombre de caract�res
28
+	// Short text length / Longueur des textes raccourcis
29
+	define('REFERENCES_SHORTEN_TEXT', '200');        // Characters count / Nombre de caract�res
30 30
 
31
-    define('REFERENCES_METAGEN_MAX_KEYWORDS', 40);
32
-    define('REFERENCES_METAGEN_KEYWORDS_ORDER', 0);
31
+	define('REFERENCES_METAGEN_MAX_KEYWORDS', 40);
32
+	define('REFERENCES_METAGEN_KEYWORDS_ORDER', 0);
33 33
 
34
-    // Automatically fill the manual date when creating a reference ? / Remplir automatiquement la date manuelle lorsqu'on crée une référence
35
-    define('REFERENCES_AUTO_FILL_MANUAL_DATE', true);
34
+	// Automatically fill the manual date when creating a reference ? / Remplir automatiquement la date manuelle lorsqu'on crée une référence
35
+	define('REFERENCES_AUTO_FILL_MANUAL_DATE', true);
36 36
 
37
-    /**
38
-     * Si la valeur est à false, alors dans les listes de recherche, côté admin, on recherche tout ce qui contient quelque chose.
39
-     * Par exemple si on tape "a", le module trouvera "abajour" et "cartable".
40
-     * Par contre si on met cette valeur à true alors le module cherchera tout ce qui commence par ...
41
-     * Par exemple si on tape "a", lemodule trouvera "abajour" MAIS PAS "cartable"
42
-     * PAR CONTRE "%a" trouvera tout ce qui contient la lettre a
43
-     */
44
-    define('REFERENCES_EXACT_SEARCH', true);
37
+	/**
38
+	 * Si la valeur est à false, alors dans les listes de recherche, côté admin, on recherche tout ce qui contient quelque chose.
39
+	 * Par exemple si on tape "a", le module trouvera "abajour" et "cartable".
40
+	 * Par contre si on met cette valeur à true alors le module cherchera tout ce qui commence par ...
41
+	 * Par exemple si on tape "a", lemodule trouvera "abajour" MAIS PAS "cartable"
42
+	 * PAR CONTRE "%a" trouvera tout ce qui contient la lettre a
43
+	 */
44
+	define('REFERENCES_EXACT_SEARCH', true);
45 45
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -20,13 +20,13 @@
 block discarded – undo
20 20
  */
21 21
 if (!defined('REFERENCES_CACHE_PATH')) {
22 22
     // Le chemin du cache (il est conseillé de le mettre en dehors de la portée du web)
23
-    define('REFERENCES_CACHE_PATH', XOOPS_UPLOAD_PATH . DIRECTORY_SEPARATOR . REFERENCES_DIRNAME . '_cache' . DIRECTORY_SEPARATOR);
23
+    define('REFERENCES_CACHE_PATH', XOOPS_UPLOAD_PATH.DIRECTORY_SEPARATOR.REFERENCES_DIRNAME.'_cache'.DIRECTORY_SEPARATOR);
24 24
 
25 25
     // Thumbs / Vignettes prefixe
26
-    define('REFERENCES_THUMBS_PREFIX', 'thumb_');        // Thumbs prefix (when thumbs are automatically created)
26
+    define('REFERENCES_THUMBS_PREFIX', 'thumb_'); // Thumbs prefix (when thumbs are automatically created)
27 27
 
28 28
     // Short text length / Longueur des textes raccourcis
29
-    define('REFERENCES_SHORTEN_TEXT', '200');        // Characters count / Nombre de caract�res
29
+    define('REFERENCES_SHORTEN_TEXT', '200'); // Characters count / Nombre de caract�res
30 30
 
31 31
     define('REFERENCES_METAGEN_MAX_KEYWORDS', 40);
32 32
     define('REFERENCES_METAGEN_KEYWORDS_ORDER', 0);
Please login to merge, or discard this patch.
header.php 2 patches
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -19,8 +19,8 @@
 block discarded – undo
19 19
  * ****************************************************************************
20 20
  */
21 21
 if (file_exists('../../mainfile.php')) {
22
-    require __DIR__ . '/../../mainfile.php';
22
+	require __DIR__ . '/../../mainfile.php';
23 23
 } elseif (file_exists('../../../mainfile.php')) {
24
-    require __DIR__ . '/../../../mainfile.php';
24
+	require __DIR__ . '/../../../mainfile.php';
25 25
 }
26 26
 require_once XOOPS_ROOT_PATH . '/modules/references/include/common.php';
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -19,8 +19,8 @@
 block discarded – undo
19 19
  * ****************************************************************************
20 20
  */
21 21
 if (file_exists('../../mainfile.php')) {
22
-    require __DIR__ . '/../../mainfile.php';
22
+    require __DIR__.'/../../mainfile.php';
23 23
 } elseif (file_exists('../../../mainfile.php')) {
24
-    require __DIR__ . '/../../../mainfile.php';
24
+    require __DIR__.'/../../../mainfile.php';
25 25
 }
26
-require_once XOOPS_ROOT_PATH . '/modules/references/include/common.php';
26
+require_once XOOPS_ROOT_PATH.'/modules/references/include/common.php';
Please login to merge, or discard this patch.
plugins/actions/newcategory/plugins.php 1 patch
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -25,44 +25,44 @@
 block discarded – undo
25 25
  */
26 26
 class referencesNewcategoryAction extends references_action
27 27
 {
28
-    public function registerEvents()
29
-    {
30
-        /**
31
-         * La liste des évènements traités par le plugin se présente sous la forme d'un tableau compposé comme ceci :
32
-         *
33
-         * Indice   Signification
34
-         * ----------------------
35
-         *    0        Evènement sur lequel se raccrocher (voir class/references_plugins.php::EVENT_ON_PRODUCT_CREATE
36
-         *    1        Priorité du plugin (de 1 à 5)
37
-         *    2        Script Php à inclure
38
-         *    3        Classe à instancier
39
-         *    4        Méthode à appeler
40
-         */
41
-        $events   = array();
42
-        $events[] = array(
43
-            references_plugins::EVENT_ON_CATEGORY_CREATE,
44
-            references_plugins::EVENT_PRIORITY_1,
45
-            basename(__FILE__),
46
-            __CLASS__,
47
-            'fireNewCategory'
48
-        );
28
+	public function registerEvents()
29
+	{
30
+		/**
31
+		 * La liste des évènements traités par le plugin se présente sous la forme d'un tableau compposé comme ceci :
32
+		 *
33
+		 * Indice   Signification
34
+		 * ----------------------
35
+		 *    0        Evènement sur lequel se raccrocher (voir class/references_plugins.php::EVENT_ON_PRODUCT_CREATE
36
+		 *    1        Priorité du plugin (de 1 à 5)
37
+		 *    2        Script Php à inclure
38
+		 *    3        Classe à instancier
39
+		 *    4        Méthode à appeler
40
+		 */
41
+		$events   = array();
42
+		$events[] = array(
43
+			references_plugins::EVENT_ON_CATEGORY_CREATE,
44
+			references_plugins::EVENT_PRIORITY_1,
45
+			basename(__FILE__),
46
+			__CLASS__,
47
+			'fireNewCategory'
48
+		);
49 49
 
50
-        return $events;
51
-    }
50
+		return $events;
51
+	}
52 52
 
53
-    /**
54
-     * Méthode appelée pour indiquer qu'une nouvelle catégorie de références a été créée
55
-     *
56
-     * @param object $parameters La catégorie qui vient d'être publiée
57
-     * @return void
58
-     */
59
-    public function fireNewCategory($parameters)
60
-    {
61
-        $category                = $parameters['category'];
62
-        $notification_handler    = xoops_getHandler('notification');
63
-        $params                  = array();
64
-        $params['CATEGORY_URL']  = $category->getUrl();
65
-        $params['CATEGORY_NAME'] = $category->getVar('category_title');
66
-        $notification_handler->triggerEvent('global', 0, 'new_category', $params);
67
-    }
53
+	/**
54
+	 * Méthode appelée pour indiquer qu'une nouvelle catégorie de références a été créée
55
+	 *
56
+	 * @param object $parameters La catégorie qui vient d'être publiée
57
+	 * @return void
58
+	 */
59
+	public function fireNewCategory($parameters)
60
+	{
61
+		$category                = $parameters['category'];
62
+		$notification_handler    = xoops_getHandler('notification');
63
+		$params                  = array();
64
+		$params['CATEGORY_URL']  = $category->getUrl();
65
+		$params['CATEGORY_NAME'] = $category->getVar('category_title');
66
+		$notification_handler->triggerEvent('global', 0, 'new_category', $params);
67
+	}
68 68
 }
Please login to merge, or discard this patch.
plugins/actions/twitter/bitly.class.php 2 patches
Indentation   +209 added lines, -209 removed lines patch added patch discarded remove patch
@@ -13,218 +13,218 @@
 block discarded – undo
13 13
 */
14 14
 
15 15
 if (class_exists('Bitly')) {
16
-    return true;
16
+	return true;
17 17
 }
18 18
 
19 19
 class Bitly
20 20
 {
21 21
 
22
-    protected $api          = 'http://api.bit.ly/';
23
-    private   $format       = 'json';
24
-    private   $version      = '2.0.1';
25
-    private   $validActions = array(
26
-        'shorten',
27
-        'stats',
28
-        'info',
29
-        'expand'
30
-    );
31
-
32
-    public function __construct($login, $apiKey)
33
-    {
34
-        $this->login        = $login;
35
-        $this->apiKey       = $apiKey;
36
-        $this->statusCode   = 'OK';
37
-        $this->errorMessage = '';
38
-        $this->errorCode    = '';
39
-        return true;
40
-    }
41
-
42
-    private function setError($message, $code = 101)
43
-    {
44
-        $this->errorCode    = $code;
45
-        $this->errorMessage = $message;
46
-        $this->statusCode   = 'ERROR';
47
-    }
48
-
49
-    public function validAction($action)
50
-    {
51
-        if (in_array($action, $this->validActions)) {
52
-            return true;
53
-        }
54
-        $this->setError("Undefined method $action", 202);
55
-        return false;
56
-    }
57
-
58
-    public function error()
59
-    {
60
-        $ret = array(
61
-            'errorCode'    => $this->errorCode,
62
-            'errorMessage' => $this->errorMessage,
63
-            'statusCode'   => $this->statusCode
64
-        );
65
-
66
-        // Function used for passing empty result sometimes.
67
-        if ($this->statusCode === 'OK') {
68
-            $ret['results'] = array();
69
-        }
70
-        if ($this->format === 'json') {
71
-            return json_encode($ret);
72
-        } else {
73
-            throw new Exception('Unsupported format');
74
-        }
75
-    }
76
-
77
-    public function shorten($message)
78
-    {
79
-
80
-        $postFields = '';
81
-        preg_match_all("/http(s?):\/\/[^( |$|\]|,|\\\)]+/i", $message, $matches);
82
-
83
-        for ($i = 0; $i < count($matches[0]); $i++) {
84
-            $curr = $matches[0][$i];
85
-            // ignore bitly urls
86
-            if (!strstr($curr, 'http://bit.ly')) {
87
-                $postFields .= '&longUrl=' . urlencode($curr);
88
-            }
89
-        }
90
-
91
-        // nothing to shorten, return empty result
92
-        if (!strlen($postFields)) {
93
-            return $this->error();
94
-        }
95
-        return $this->process('shorten', $postFields);
96
-    }
97
-
98
-    public function expand($message)
99
-    {
100
-        $postFields = '&hash=' . $this->getHash($message);
101
-        return $this->process('expand', $postFields);
102
-    }
103
-
104
-    public function info($bitlyUrl)
105
-    {
106
-        $hash       = $this->getHash($bitlyUrl);
107
-        $postFields = '&hash=' . $hash;
108
-        return $this->process('info', $postFields);
109
-    }
110
-
111
-    public function stats($bitlyUrl)
112
-    {
113
-        // Take only first hash or url. Ignore others.
114
-        $a          = split(',', $bitlyUrl);
115
-        $postFields = '&hash=' . $this->getHash($a[0]);
116
-        return $this->process('stats', $postFields);
117
-    }
118
-
119
-    protected function process($action, $postFields)
120
-    {
121
-        $ch = curl_init($this->api . $action);
122
-
123
-        $postFields = 'version=' . $this->version . $postFields;
124
-        $postFields .= '&format=' . $this->format;
125
-        $postFields .= '&history=1';
126
-
127
-        curl_setopt($ch, CURLOPT_USERPWD, $this->login . ':' . $this->apiKey);
128
-        curl_setopt($ch, CURLOPT_POST, 1);
129
-        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
130
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
131
-
132
-        $response = curl_exec($ch);
133
-
134
-        curl_close($ch);
135
-
136
-        return $response;
137
-    }
138
-
139
-    public function setReturnFormat($format)
140
-    {
141
-        // needed for restoration
142
-        $this->oldFormat = $this->format;
143
-        $this->format    = $format;
144
-        return $this->format;
145
-    }
146
-
147
-    private function restoreFormat()
148
-    {
149
-        if (!empty($this->oldFormat)) {
150
-            $this->format = $this->oldFormat;
151
-        }
152
-        return $this->format;
153
-    }
154
-
155
-    // expect url, shortened url or hash
156
-    public function getHash($message)
157
-    {
158
-        // if url and not bit.ly get shortened first
159
-        if (strstr($message, 'http://') && !strstr($message, 'http://bit.ly')) {
160
-            $message = $this->shortenSingle($message);
161
-        }
162
-        $hash = str_replace('http://bit.ly/', '', $message);
163
-        return $hash;
164
-    }
165
-
166
-    public function shortenSingle($message)
167
-    {
168
-        $this->setReturnFormat('json');
169
-        $data = json_decode($this->shorten($message), true);
170
-        // return to previous state.
171
-        $this->restoreFormat();
172
-
173
-        // replace every long url with short one
174
-        foreach ($data['results'] as $url => $d) {
175
-            $message = str_replace($url, $d['shortUrl'], $message);
176
-        }
177
-        return $message;
178
-    }
179
-
180
-    public function expandSingle($shortUrl)
181
-    {
182
-        $this->setReturnFormat('json');
183
-        $data = json_decode($this->expand($shortUrl), true);
184
-        $this->restoreFormat();
185
-        return $data['results'][$this->getHash($shortUrl)]['longUrl'];
186
-    }
187
-
188
-    public function getInfoArray($url)
189
-    {
190
-        $this->setReturnFormat('json');
191
-        $json = $this->info($url);
192
-        $this->restoreFormat();
193
-        $data = json_decode($json, true);
194
-
195
-        $this->infoArray = array_pop($data['results']);
196
-        return $this->infoArray;
197
-    }
198
-
199
-    public function getStatsArray($url)
200
-    {
201
-        $this->setReturnFormat('json');
202
-        $json = $this->stats($url);
203
-        $this->restoreFormat();
204
-        $data             = json_decode($json, true);
205
-        $this->statsArray = $data['results'];
206
-        return $this->statsArray;
207
-    }
208
-
209
-    public function getClicks()
210
-    {
211
-        return $this->statsArray['clicks'];
212
-    }
213
-
214
-    // get thumbnail (small, middle, large)
215
-    public function getThumbnail($size = 'small')
216
-    {
217
-        if (!in_array($size, array('small', 'medium', 'large'))) {
218
-            throw new Exception('Invalid size value');
219
-        }
220
-        if (empty($this->infoArray)) {
221
-            throw new Exception('Info not loaded');
222
-        }
223
-        return $this->infoArray['thumbnail'][$size];
224
-    }
225
-
226
-    public function getTitle()
227
-    {
228
-        return $this->infoArray['htmlTitle'];
229
-    }
22
+	protected $api          = 'http://api.bit.ly/';
23
+	private   $format       = 'json';
24
+	private   $version      = '2.0.1';
25
+	private   $validActions = array(
26
+		'shorten',
27
+		'stats',
28
+		'info',
29
+		'expand'
30
+	);
31
+
32
+	public function __construct($login, $apiKey)
33
+	{
34
+		$this->login        = $login;
35
+		$this->apiKey       = $apiKey;
36
+		$this->statusCode   = 'OK';
37
+		$this->errorMessage = '';
38
+		$this->errorCode    = '';
39
+		return true;
40
+	}
41
+
42
+	private function setError($message, $code = 101)
43
+	{
44
+		$this->errorCode    = $code;
45
+		$this->errorMessage = $message;
46
+		$this->statusCode   = 'ERROR';
47
+	}
48
+
49
+	public function validAction($action)
50
+	{
51
+		if (in_array($action, $this->validActions)) {
52
+			return true;
53
+		}
54
+		$this->setError("Undefined method $action", 202);
55
+		return false;
56
+	}
57
+
58
+	public function error()
59
+	{
60
+		$ret = array(
61
+			'errorCode'    => $this->errorCode,
62
+			'errorMessage' => $this->errorMessage,
63
+			'statusCode'   => $this->statusCode
64
+		);
65
+
66
+		// Function used for passing empty result sometimes.
67
+		if ($this->statusCode === 'OK') {
68
+			$ret['results'] = array();
69
+		}
70
+		if ($this->format === 'json') {
71
+			return json_encode($ret);
72
+		} else {
73
+			throw new Exception('Unsupported format');
74
+		}
75
+	}
76
+
77
+	public function shorten($message)
78
+	{
79
+
80
+		$postFields = '';
81
+		preg_match_all("/http(s?):\/\/[^( |$|\]|,|\\\)]+/i", $message, $matches);
82
+
83
+		for ($i = 0; $i < count($matches[0]); $i++) {
84
+			$curr = $matches[0][$i];
85
+			// ignore bitly urls
86
+			if (!strstr($curr, 'http://bit.ly')) {
87
+				$postFields .= '&longUrl=' . urlencode($curr);
88
+			}
89
+		}
90
+
91
+		// nothing to shorten, return empty result
92
+		if (!strlen($postFields)) {
93
+			return $this->error();
94
+		}
95
+		return $this->process('shorten', $postFields);
96
+	}
97
+
98
+	public function expand($message)
99
+	{
100
+		$postFields = '&hash=' . $this->getHash($message);
101
+		return $this->process('expand', $postFields);
102
+	}
103
+
104
+	public function info($bitlyUrl)
105
+	{
106
+		$hash       = $this->getHash($bitlyUrl);
107
+		$postFields = '&hash=' . $hash;
108
+		return $this->process('info', $postFields);
109
+	}
110
+
111
+	public function stats($bitlyUrl)
112
+	{
113
+		// Take only first hash or url. Ignore others.
114
+		$a          = split(',', $bitlyUrl);
115
+		$postFields = '&hash=' . $this->getHash($a[0]);
116
+		return $this->process('stats', $postFields);
117
+	}
118
+
119
+	protected function process($action, $postFields)
120
+	{
121
+		$ch = curl_init($this->api . $action);
122
+
123
+		$postFields = 'version=' . $this->version . $postFields;
124
+		$postFields .= '&format=' . $this->format;
125
+		$postFields .= '&history=1';
126
+
127
+		curl_setopt($ch, CURLOPT_USERPWD, $this->login . ':' . $this->apiKey);
128
+		curl_setopt($ch, CURLOPT_POST, 1);
129
+		curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
130
+		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
131
+
132
+		$response = curl_exec($ch);
133
+
134
+		curl_close($ch);
135
+
136
+		return $response;
137
+	}
138
+
139
+	public function setReturnFormat($format)
140
+	{
141
+		// needed for restoration
142
+		$this->oldFormat = $this->format;
143
+		$this->format    = $format;
144
+		return $this->format;
145
+	}
146
+
147
+	private function restoreFormat()
148
+	{
149
+		if (!empty($this->oldFormat)) {
150
+			$this->format = $this->oldFormat;
151
+		}
152
+		return $this->format;
153
+	}
154
+
155
+	// expect url, shortened url or hash
156
+	public function getHash($message)
157
+	{
158
+		// if url and not bit.ly get shortened first
159
+		if (strstr($message, 'http://') && !strstr($message, 'http://bit.ly')) {
160
+			$message = $this->shortenSingle($message);
161
+		}
162
+		$hash = str_replace('http://bit.ly/', '', $message);
163
+		return $hash;
164
+	}
165
+
166
+	public function shortenSingle($message)
167
+	{
168
+		$this->setReturnFormat('json');
169
+		$data = json_decode($this->shorten($message), true);
170
+		// return to previous state.
171
+		$this->restoreFormat();
172
+
173
+		// replace every long url with short one
174
+		foreach ($data['results'] as $url => $d) {
175
+			$message = str_replace($url, $d['shortUrl'], $message);
176
+		}
177
+		return $message;
178
+	}
179
+
180
+	public function expandSingle($shortUrl)
181
+	{
182
+		$this->setReturnFormat('json');
183
+		$data = json_decode($this->expand($shortUrl), true);
184
+		$this->restoreFormat();
185
+		return $data['results'][$this->getHash($shortUrl)]['longUrl'];
186
+	}
187
+
188
+	public function getInfoArray($url)
189
+	{
190
+		$this->setReturnFormat('json');
191
+		$json = $this->info($url);
192
+		$this->restoreFormat();
193
+		$data = json_decode($json, true);
194
+
195
+		$this->infoArray = array_pop($data['results']);
196
+		return $this->infoArray;
197
+	}
198
+
199
+	public function getStatsArray($url)
200
+	{
201
+		$this->setReturnFormat('json');
202
+		$json = $this->stats($url);
203
+		$this->restoreFormat();
204
+		$data             = json_decode($json, true);
205
+		$this->statsArray = $data['results'];
206
+		return $this->statsArray;
207
+	}
208
+
209
+	public function getClicks()
210
+	{
211
+		return $this->statsArray['clicks'];
212
+	}
213
+
214
+	// get thumbnail (small, middle, large)
215
+	public function getThumbnail($size = 'small')
216
+	{
217
+		if (!in_array($size, array('small', 'medium', 'large'))) {
218
+			throw new Exception('Invalid size value');
219
+		}
220
+		if (empty($this->infoArray)) {
221
+			throw new Exception('Info not loaded');
222
+		}
223
+		return $this->infoArray['thumbnail'][$size];
224
+	}
225
+
226
+	public function getTitle()
227
+	{
228
+		return $this->infoArray['htmlTitle'];
229
+	}
230 230
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
             $curr = $matches[0][$i];
85 85
             // ignore bitly urls
86 86
             if (!strstr($curr, 'http://bit.ly')) {
87
-                $postFields .= '&longUrl=' . urlencode($curr);
87
+                $postFields .= '&longUrl='.urlencode($curr);
88 88
             }
89 89
         }
90 90
 
@@ -97,14 +97,14 @@  discard block
 block discarded – undo
97 97
 
98 98
     public function expand($message)
99 99
     {
100
-        $postFields = '&hash=' . $this->getHash($message);
100
+        $postFields = '&hash='.$this->getHash($message);
101 101
         return $this->process('expand', $postFields);
102 102
     }
103 103
 
104 104
     public function info($bitlyUrl)
105 105
     {
106 106
         $hash       = $this->getHash($bitlyUrl);
107
-        $postFields = '&hash=' . $hash;
107
+        $postFields = '&hash='.$hash;
108 108
         return $this->process('info', $postFields);
109 109
     }
110 110
 
@@ -112,19 +112,19 @@  discard block
 block discarded – undo
112 112
     {
113 113
         // Take only first hash or url. Ignore others.
114 114
         $a          = split(',', $bitlyUrl);
115
-        $postFields = '&hash=' . $this->getHash($a[0]);
115
+        $postFields = '&hash='.$this->getHash($a[0]);
116 116
         return $this->process('stats', $postFields);
117 117
     }
118 118
 
119 119
     protected function process($action, $postFields)
120 120
     {
121
-        $ch = curl_init($this->api . $action);
121
+        $ch = curl_init($this->api.$action);
122 122
 
123
-        $postFields = 'version=' . $this->version . $postFields;
124
-        $postFields .= '&format=' . $this->format;
123
+        $postFields = 'version='.$this->version.$postFields;
124
+        $postFields .= '&format='.$this->format;
125 125
         $postFields .= '&history=1';
126 126
 
127
-        curl_setopt($ch, CURLOPT_USERPWD, $this->login . ':' . $this->apiKey);
127
+        curl_setopt($ch, CURLOPT_USERPWD, $this->login.':'.$this->apiKey);
128 128
         curl_setopt($ch, CURLOPT_POST, 1);
129 129
         curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
130 130
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Please login to merge, or discard this patch.