ub_total + self.vat 147
+        super(Purchase, self).save(*args, **kwargs)
148
+
149
+class Sale(GenericModel, models.Model):
150
+    product = models.ForeignKey('Product', on_delete=models.DO_NOTHING, null=False, blank=False)
151
+    store = models.ForeignKey('Store', on_delete=models.DO_NOTHING, null=False, blank=False)
152
+    sku = models.ForeignKey('ProductSKU', on_delete=models.DO_NOTHING, null=False, blank=False)
153
+    price = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=7)
154
+    n_unit = models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True)
155
+    unit_name = models.CharField(max_length=200, null=True)
156
+    buyer = models.ForeignKey('Buyer', on_delete=models.DO_NOTHING, null=False, blank=False)
157
+
158
+
159
+    sub_total = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=10)
160
+    vat = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=10)
161
+    total = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=10)
162
+
163
+    def save(self, *args, **kwargs):
164
+        self.sub_total = self.price * self.n_unit
165
+        self.vat  = self.sub_total * decimal.Decimal(VAT)
166
+        self.total = self.sub_total + self.vat
167
+        super(Sale, self).save(*args, **kwargs)
168
+
93 169
 class Product(GenericModel, models.Model ):
94 170
     name = models.CharField(max_length=200)
95 171
     code = models.CharField(max_length=200)
96 172
     product_type = TreeForeignKey('ProductType', on_delete=models.SET_NULL, null=True)
97 173
     description = models.TextField(blank=True, null=True)
98 174
     store = models.ForeignKey('Store', on_delete=models.CASCADE, null=True, blank=False)
99
-    price = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=7)
175
+    price = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=10)
176
+
177
+
178
+    details  = models.JSONField(null=True, blank=True)
179
+
180
+    n_unit = models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True)
181
+    unit_name = models.CharField(max_length=200, null=True)
182
+
183
+    def __str__(self):
184
+        return f"{self.name} {self.code}"
185
+
186
+class Vendor(GenericModel, models.Model ):
187
+    name = models.CharField(max_length=200)
188
+    code = models.CharField(max_length=200)
189
+    #product_type = TreeForeignKey('ProductType', on_delete=models.SET_NULL, null=True)
190
+    product = models.ForeignKey('Product', on_delete=models.CASCADE)
191
+    description = models.TextField(blank=True, null=True)
192
+    store = models.ForeignKey('Store', on_delete=models.CASCADE, null=True, blank=False)
193
+    price = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=10)
194
+
100 195
 
101 196
     details  = models.JSONField(null=True, blank=True)
102 197
 
103 198
     n_unit = models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True)
104 199
     unit_name = models.CharField(max_length=200, null=True)
105 200
 
201
+    tel = models.CharField(max_length=100, null=True, blank=True)
202
+    line_id = models.CharField(max_length=100, null=True, blank=True)
203
+    email = models.EmailField(null=True, blank=True)
204
+
205
+    address_text = models.TextField(blank=False, null=False)
206
+    address = map_fields.AddressField(max_length=200)
207
+    geolocation = map_fields.GeoLocationField(max_length=100)
208
+
209
+
106 210
     def __str__(self):
107 211
         return f"{self.name} {self.code}"
108 212
 
213
+
109 214
 class ProductSKU(GenericModel, models.Model ):
110 215
     sku = models.CharField(max_length=200)
111 216
     product  = models.ForeignKey('Product', on_delete=models.CASCADE, null=True)
@@ -117,8 +222,12 @@ class ProductSKU(GenericModel, models.Model ):
117 222
     n_unit = models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True)
118 223
     unit_name = models.CharField(max_length=200, null=True)
119 224
 
225
+    def __str__(self):
226
+        return f"{self.sku} {self.product} @{self.price}(THB)"
227
+
120 228
 class Photo(GenericModel, models.Model):
121 229
     name = models.CharField(max_length=200,  blank=True)
230
+    order_n = models.IntegerField(default=0, blank=True)
122 231
     photo  = models.ImageField(upload_to="uploads/%Y/%m/%d/", blank=False, verbose_name="Photo")
123 232
     product = models.ForeignKey('Product', on_delete=models.CASCADE, null=True)
124 233
 

+ 17 - 0
app/fruit/templates/fruit/_paging.html

@@ -0,0 +1,17 @@
1
+<div class="pagination">
2
+    <span class="step-links">
3
+        {% if page_obj.has_previous %}
4
+            <a href="?page=1">&laquo; first</a>
5
+            <a href="?page={{ page_obj.previous_page_number }}">previous</a>
6
+        {% endif %}
7
+
8
+        <span class="current">
9
+            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
10
+        </span>
11
+
12
+        {% if page_obj.has_next %}
13
+            <a href="?page={{ page_obj.next_page_number }}">next</a>
14
+            <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a>
15
+        {% endif %}
16
+    </span>
17
+</div>

+ 13 - 0
app/fruit/templates/fruit/_searchcenter.html

@@ -0,0 +1,13 @@
1
+{% load crispy_forms_tags %}
2
+<form method="get">
3
+    <div class='row'>
4
+        <!--
5
+            {{ filter.form.fields }} -->
6
+    {% for f0  in filter.form %}
7
+        <div class='col-md-3'>
8
+            {{ f0 | as_crispy_field}}  
9
+        </div>
10
+    {% endfor %}
11
+    </div>
12
+    <input type="submit" class='btn btn-primary' value='Search'/>
13
+</form>

+ 25 - 0
app/fruit/templates/fruit/inbox_form.html

@@ -0,0 +1,25 @@
1
+{% extends "fruit/inbox_index.html" %}
2
+{% load static %}
3
+{% load crispy_forms_tags %}
4
+{% load django_bootstrap_breadcrumbs %}
5
+
6
+{% block header %}            
7
+{{ form.media  }}
8
+{% endblock %}
9
+
10
+{% block breadcrumbs %}
11
+    {{ block.super }}
12
+    {% breadcrumb "Inbox Form" "fruit:inbox_edit" form.instance.pk %}
13
+{% endblock %}
14
+
15
+{% block store_main %}
16
+<h2>Inbox Form</h2>
17
+<form  method="post" enctype="multipart/form-data">
18
+    {% csrf_token %}
19
+    {{ form | crispy  }}
20
+    <br>
21
+    <input type='submit' class='btn btn-primary' value="Update" />
22
+
23
+</form>
24
+
25
+{% endblock %}

+ 50 - 0
app/fruit/templates/fruit/inbox_index.html

@@ -0,0 +1,50 @@
1
+{% extends "fruit/mystore.html" %}
2
+{% load static %}
3
+{% load crispy_forms_tags %}
4
+
5
+{% block header %}            
6
+{% endblock %}
7
+
8
+{% load django_bootstrap_breadcrumbs %}
9
+{% block breadcrumbs %}
10
+    {{ block.super }}
11
+    {% breadcrumb "Inboxes" "fruit:inbox_index" %}
12
+{% endblock %}
13
+
14
+{% block store_main %}
15
+<!--
16
+<a  class='btn btn-primary' href="{% url "fruit:product_create" %}">Create Product</a> -->
17
+<hr>
18
+<h2>
19
+    Inbox Index</h2>
20
+{% include "fruit/_searchcenter.html" %}
21
+<hr>
22
+<table class='table table-borded table-striped'>
23
+    <thead>
24
+        <tr>
25
+            <th>ID</th>
26
+            <th>Store</th>
27
+            <th>Product</th>
28
+            <th>Buyer</th>
29
+            <th>Subject</th>
30
+            <th>Body</th>
31
+            <th>Status</th>
32
+            <th>Created At</th></tr>
33
+    </thead>
34
+    <tbody>
35
+{% for p in page_obj %}
36
+        <tr>
37
+            <td><a href="{% url "fruit:inbox_edit" pk=p.pk %}">{{ p.id }}</a></td><td>{{ p.product }}</td>
38
+            <td>{{ p.store}}</td>
39
+            <td>{{ p.product }}</td>
40
+            <td>{{ p.buyer }}</td>
41
+            <td>{{ p.subject }}</td>
42
+            <td>{{ p.body }}</td>
43
+            <td>{{ p.status }}</td>
44
+            <td>{{ p.created_at }}</td>
45
+        </tr>
46
+{% endfor %}
47
+    </tbody>
48
+</table>
49
+{% include "fruit/_paging.html" %}
50
+{% endblock %}

+ 12 - 3
app/fruit/templates/fruit/mystore.html

@@ -1,6 +1,7 @@
1 1
 {% extends "front/base.html" %}
2 2
 {% load static %}
3 3
 {% load crispy_forms_tags %}
4
+{% load django_bootstrap_breadcrumbs %}
4 5
 
5 6
 {% block header %}            
6 7
 {{ storeForm.media  }}
@@ -8,21 +9,29 @@
8 9
 
9 10
 {% block content %}
10 11
 <h1>My Store</h1>
12
+<!-- 
11 13
 <form method=post>
12 14
     {% csrf_token %}
13 15
     <input type='text' name='name' class='form-control' placeholder='Store Name'/>
14 16
     <input type='submit' class='btn btn-primary' name='createStore' value="Create Store" />
15 17
 </form>
16
-<hr>
18
+<hr> -->
17 19
 <div class="d-flex align-items-start">
18 20
   <div class="nav flex-column nav-pills me-3 col-md-3 col-lg-2" id="v-pills-tab" role="tablist" aria-orientation="vertical">
19 21
       <a class="nav-link {{ mystore|yesno:"active," }}" id="v-pills-home-tab"  href="{% url "fruit:mystore" %}" type="button" role="tab" aria-controls="v-pills-home" aria-selected="true">Info</a>
20 22
       <a class="nav-link {{ product|yesno:"active," }}" id="v-pills-profile-tab"  href="{% url "fruit:product_index" %}" type="button" role="tab" aria-controls="v-pills-profile" aria-selected="false">Products</a>
21
-    <a class="nav-link" id="v-pills-messages-tab" data-toggle="pill" data-bs-target="#v-pills-messages" type="button" role="tab" aria-controls="v-pills-messages" aria-selected="false">Inbox</a>
22
-    <a class="nav-link" id="v-pills-settings-tab" data-toggle="pill" data-bs-target="#v-pills-settings" type="button" role="tab" aria-controls="v-pills-settings" aria-selected="false">Saled Items</a>
23
+    <a class="nav-link" id="v-pills-messages-tab" href="{% url "fruit:inbox_index" %}" type="button" role="tab" aria-controls="v-pills-messages" aria-selected="false">Inbox</a>
24
+    <a class="nav-link {{ sale_active|yesno:"active," }}" id="v-pills-settings-tab" href="{% url "fruit:sale_index" %}"  type="button" role="tab" aria-controls="v-pills-settings" aria-selected="false">Saled Items</a>
23 25
     <a class="nav-link" id="v-pills-vendor-tab" data-toggle="pill" data-bs-target="#v-pills-vendor" type="button" role="tab" aria-controls="v-pills-vendor" aria-selected="false">Vendors</a>
24 26
   </div>
25 27
   <div class="tab-content p-3 col-md-9 col-lg-10" id="v-pills-tabContent">
28
+      {% block breadcrumbs %}
29
+          {% clear_breadcrumbs %}
30
+          {% breadcrumb "My Store" "fruit:mystore" %}
31
+      {% endblock %}
32
+
33
+
34
+    {% render_breadcrumbs %} 
26 35
       {% block store_main %}
27 36
       {% endblock %}
28 37
   </div>

+ 36 - 30
app/fruit/templates/fruit/product_form.html

@@ -1,4 +1,4 @@
1
-{% extends "fruit/mystore.html" %}
1
+{% extends "fruit/product_index.html" %}
2 2
 {% load static %}
3 3
 {% load crispy_forms_tags %}
4 4
 
@@ -7,41 +7,47 @@
7 7
 {{ form2.media  }}
8 8
 {% endblock %}
9 9
 
10
+{% load django_bootstrap_breadcrumbs %}
11
+{% block breadcrumbs %}
12
+    {{ block.super }}
13
+    {% breadcrumb "Product Edit" "fruit:product_edit" pid  %}
14
+{% endblock %}
15
+
10 16
 {% block store_main %}
11 17
     Create Product
12 18
 
19
+
13 20
 <form  method="post" enctype="multipart/form-data">
14 21
     {% csrf_token %}
15 22
     {{ form | crispy  }}
16
-    <fieldset class="border p-2">
17
-        <legend class='w-auto d-inline-block form-legend p-3'>Photos</legend>
18
-        {{ form2.management_form }}
19
-        <div class='row'>
20
-        {% for f0  in form2 %}
21
-        <div class='col-md-3'>
22
-        <!-- {{ f0.fields }} -->
23
-
24
-            {{ f0.id  | as_crispy_field }}
25
-            {{ f0.name | as_crispy_field }}
26
-            {% if f0.instance.photo %}
27
-            <a href="{{ f0.instance.photo.url }}" target="_blank">
28
-                <img src="{{ f0.instance.photo.url  }}" width='100%' style='max-height:200px'></a>
29
-            {% endif %}
30
-            {{ f0.photo | as_crispy_field }}
31
-            
32
-            {{ f0.product | as_crispy_field }}
33
-            {{ f0.DELETE | as_crispy_field }}
34
-        </div>
35
-        {% endfor %}
36
-        </div>
37
-    </fieldset>
38
-    <br>
39
-    <input type='submit' class='btn btn-primary' name='updateStore' value="Update" />
23
+        <fieldset class="border p-2 row">
24
+            <legend class='w-auto d-inline-block form-legend p-3'>Photos</legend>
25
+            {{ form2.management_form }}
26
+            {% for f0  in form2 %}
27
+            <div class='col-md-3 border'>
28
+            <!-- {{ f0.fields }} -->
29
+
30
+                {{ f0.id  | as_crispy_field }}
31
+                {{ f0.name | as_crispy_field }}
32
+                {% if f0.instance.photo %}
33
+                <a href="{{ f0.instance.photo.url }}" target="_blank">
34
+                    <img src="{{ f0.instance.photo.url  }}" width='100%' style='max-height:200px'></a>
35
+                {% endif %}
36
+                {{ f0.photo | as_crispy_field }}
37
+                
38
+                {{ f0.order_n  | as_crispy_field }}
39
+                {{ f0.product | as_crispy_field }}
40
+                {{ f0.DELETE | as_crispy_field }}
41
+            </div>
42
+            {% endfor %}
43
+        </fieldset>
44
+        <br>
45
+        <input type='submit' class='btn btn-primary' name='updateStore' value="Update" />
40 46
 
41
-</form>
42
-<hr>
43
-<h2>SKUs</h2>
44
-<a href="{% url "fruit:create_sku" pk=object.pk %}" class='btn btn-primary'>Create SKU</a><br><br>
47
+    </form>
48
+    <hr>
49
+    <h2>SKUs</h2>
50
+    <a href="{% url "fruit:create_sku" pk=obj.pk %}" class='btn btn-primary'>Create SKU</a><br><br>
45 51
 
46 52
 <table class='table table-bordered  table-striped'>
47 53
     <thead>
@@ -50,7 +56,7 @@
50 56
     </thead>
51 57
     <tbody>
52 58
         
53
-        {% for o in  object.productsku_set.all %}
59
+        {% for o in  obj.productsku_set.all %}
54 60
             <tr>
55 61
                 <td><a href="{% url "fruit:edit_sku" pk=o.pk %}">{{ o.sku }}</a></td>
56 62
                 <td>{{ o.created_at }}</td>

+ 17 - 6
app/fruit/templates/fruit/product_index.html

@@ -5,21 +5,32 @@
5 5
 {% block header %}            
6 6
 {% endblock %}
7 7
 
8
+{% load django_bootstrap_breadcrumbs %}
9
+{% block breadcrumbs %}
10
+    {{ block.super }}
11
+    {% breadcrumb "Products" "fruit:product_index" %}
12
+{% endblock %}
13
+
8 14
 {% block store_main %}
9
-<a  href="{% url "fruit:product_create" %}">Create Product</a>
15
+<a  class='btn btn-primary' href="{% url "fruit:product_create" %}">Create Product</a>
16
+<hr>
17
+<h2>
18
+    Product Index</h2>
19
+{% include "fruit/_searchcenter.html" %}
10 20
 <hr>
11
-Product Index
12
-{{ products }}
21
+<!--
22
+    {{ products }} -->
13 23
 <table class='table table-borded table-striped'>
14 24
     <thead>
15
-        <tr><th>ID</th><th>Name</th><th>Created At</th></tr>
25
+        <tr><th>ID</th><th>Name</th><th>Price</th><th>Created At</th></tr>
16 26
     </thead>
17 27
     <tbody>
18
-{% for p in products %}
28
+{% for p in page_obj %}
19 29
         <tr>
20
-            <td><a href="{% url "fruit:product_edit" pk=p.pk %}">{{ p.id }}</a></td><td>{{ p.name }}</td><td>{{ p.created_at }}</td>
30
+            <td><a href="{% url "fruit:product_edit" pk=p.pk %}">{{ p.id }}</a></td><td>{{ p.name }}</td><td>{% firstof p.price  "-" %}</td><td>{{ p.created_at }}</td>
21 31
         </tr>
22 32
 {% endfor %}
23 33
     </tbody>
24 34
 </table>
35
+{% include "fruit/_paging.html" %}
25 36
 {% endblock %}

+ 25 - 0
app/fruit/templates/fruit/sale_form.html

@@ -0,0 +1,25 @@
1
+{% extends "fruit/sale_index.html" %}
2
+{% load static %}
3
+{% load crispy_forms_tags %}
4
+{% load django_bootstrap_breadcrumbs %}
5
+
6
+{% block header %}            
7
+{{ form.media  }}
8
+{% endblock %}
9
+
10
+{% block breadcrumbs %}
11
+    {{ block.super }}
12
+    {% breadcrumb "Sales Form" "fruit:sale_edit" form.instance.pk %}
13
+{% endblock %}
14
+
15
+{% block store_main %}
16
+<h2>Sale Form</h2>
17
+<form  method="post" enctype="multipart/form-data">
18
+    {% csrf_token %}
19
+    {{ form | crispy  }}
20
+    <br>
21
+    <input type='submit' class='btn btn-primary' value="Update" />
22
+
23
+</form>
24
+
25
+{% endblock %}

+ 41 - 0
app/fruit/templates/fruit/sale_index.html

@@ -0,0 +1,41 @@
1
+{% extends "fruit/mystore.html" %}
2
+{% load static %}
3
+{% load crispy_forms_tags %}
4
+
5
+{% block header %}            
6
+{% endblock %}
7
+
8
+{% load django_bootstrap_breadcrumbs %}
9
+{% block breadcrumbs %}
10
+    {{ block.super }}
11
+    {% breadcrumb "Sales" "fruit:sale_index" %}
12
+{% endblock %}
13
+
14
+{% block store_main %}
15
+<!--
16
+<a  class='btn btn-primary' href="{% url "fruit:product_create" %}">Create Product</a> -->
17
+<hr>
18
+<h2>
19
+    Sale Index</h2>
20
+{% include "fruit/_searchcenter.html" %}
21
+<hr>
22
+<table class='table table-borded table-striped'>
23
+    <thead>
24
+        <tr><th>ID</th><th>Product</th><th>SKU</th><th>Price</th><th>Unit(s)</th><th>UName</th><th>Total</th><th>Buyer</th><th>Created At</th></tr>
25
+    </thead>
26
+    <tbody>
27
+{% for p in page_obj %}
28
+        <tr>
29
+            <td><a href="{% url "fruit:sale_edit" pk=p.pk %}">{{ p.id }}</a></td><td>{{ p.product }}</td>
30
+            <td>{{ p.sku }}</td>
31
+            <td>{{ p.n_unit }}</td>
32
+            <td>{{ p.unit_name }}</td>
33
+            <td>{{ p.total }}</td>
34
+            <td>{{ p.buyer }}</td>
35
+            <td>{% firstof p.price  "-" %}</td><td>{{ p.created_at }}</td>
36
+        </tr>
37
+{% endfor %}
38
+    </tbody>
39
+</table>
40
+{% include "fruit/_paging.html" %}
41
+{% endblock %}

+ 7 - 1
app/fruit/templates/fruit/sku_form.html

@@ -1,4 +1,4 @@
1
-{% extends "fruit/mystore.html" %}
1
+{% extends "fruit/product_form.html" %}
2 2
 {% load static %}
3 3
 {% load crispy_forms_tags %}
4 4
 
@@ -6,6 +6,12 @@
6 6
 {{ form.media  }}
7 7
 {% endblock %}
8 8
 
9
+{% load django_bootstrap_breadcrumbs %}
10
+{% block breadcrumbs %}
11
+    {{ block.super }}
12
+    {% breadcrumb "SKU Edit" "fruit:sku_edit" pk=form.instance.pk  %}
13
+{% endblock %}
14
+
9 15
 {% block store_main %}
10 16
     SKU Form
11 17
 

+ 4 - 0
app/fruit/urls.py

@@ -11,6 +11,10 @@ urlpatterns = [
11 11
     path('sku/<pk>', views.edit_sku, name='edit_sku'),
12 12
     path('products/', views.product_index, name='product_index'),
13 13
     path('products/<pk>', views.product_edit, name='product_edit'),
14
+    path('sales/', views.sale_index, name='sale_index'),
15
+    path('sales/<pk>', views.sale_edit, name='sale_edit'),
16
+    path('inbox/', views.inbox_index, name='inbox_index'),
17
+    path('inbox/<pk>', views.inbox_edit, name='inbox_edit'),
14 18
     path('signup', views.signup, name='signup'),
15 19
 ]
16 20
 

+ 98 - 6
app/fruit/views.py

@@ -6,9 +6,10 @@ from django.contrib.auth.forms import UserCreationForm
6 6
 from django.urls import reverse
7 7
 from django.contrib.auth.decorators import login_required
8 8
 
9
-from fruit.models import Store, Product, Photo, ProductSKU
10
-from .forms import StoreForm, ProductForm, PhotoFormSet, InlinePhotoFormset, ProductSKUForm
9
+from fruit.models import Store, Product, Photo, ProductSKU, Sale, Inbox
10
+from .forms import StoreForm, ProductForm, InboxForm, SaleForm,  PhotoFormSet, InlinePhotoFormset, ProductSKUForm, ProductFilter, SaleFilter, InboxFilter
11 11
 from django.contrib import messages
12
+from django.core.paginator import Paginator
12 13
 
13 14
 
14 15
 def index(request):
@@ -48,7 +49,27 @@ def mystore(request):
48 49
 def product_index(request):
49 50
     stores = request.user.store_created.all().order_by("-created_at")
50 51
     products = stores[0].product_set.all().order_by("-created_at")
51
-    return render(request, 'fruit/product_index.html', {'products': products, 'product': True})
52
+
53
+    f = ProductFilter(request.GET, queryset=products)
54
+
55
+    paginator = Paginator(f.qs, 25)
56
+    page_number = request.GET.get('page')
57
+    page_obj = paginator.get_page(page_number)
58
+
59
+    return render(request, 'fruit/product_index.html', {'products': products, 'product': True, 'page_obj': page_obj, 'filter': f})
60
+
61
+@login_required
62
+def sale_index(request):
63
+    stores = request.user.store_created.all().order_by("-created_at")
64
+    o_qs = stores[0].sale_set.all().order_by("-created_at")
65
+
66
+    f = SaleFilter(request.GET, queryset=o_qs)
67
+
68
+    paginator = Paginator(f.qs, 25)
69
+    page_number = request.GET.get('page')
70
+    page_obj = paginator.get_page(page_number)
71
+
72
+    return render(request, 'fruit/sale_index.html', {'o_qs': o_qs, 'sale_active': True, 'page_obj': page_obj, 'filter': f})
52 73
 
53 74
 @login_required
54 75
 def create_product(request):
@@ -97,11 +118,14 @@ def create_sku(request, pk):
97 118
             message.error(request, "SKU  created failed")
98 119
             return redirect("fruit:create_sku", pk=int(pk))
99 120
 
100
-    return render(request, 'fruit/sku_form.html', {'form': form})
121
+    return render(request, 'fruit/sku_form.html', {'form': form, 'pid': p.pk})
101 122
 
102 123
 @login_required
103 124
 def edit_sku(request, pk):
125
+
104 126
     p = ProductSKU.objects.get(pk=pk)
127
+    p0 = p.product
128
+
105 129
     form = ProductSKUForm(instance=p)
106 130
     if request.method == "POST":
107 131
         form = ProductSKUForm(request.POST)
@@ -113,7 +137,7 @@ def edit_sku(request, pk):
113 137
             message.error(request, "SKU  created failed")
114 138
             return redirect("fruit:create_sku", pk=int(pk))
115 139
 
116
-    return render(request, 'fruit/sku_form.html', {'form': form})
140
+    return render(request, 'fruit/sku_form.html', {'form': form, 'pid': p0.pk})
117 141
 
118 142
 @login_required
119 143
 def product_edit(request, pk):
@@ -151,7 +175,75 @@ def product_edit(request, pk):
151 175
 
152 176
         return redirect("fruit:product_edit", pk =  int(pk))
153 177
 
154
-    return render(request, 'fruit/product_form.html', {'product': True, 'form': form, 'form2': form2, 'object': product })
178
+    return render(request, 'fruit/product_form.html', {'product': True, 'form': form, 'form2': form2, 'obj': product })
179
+
180
+@login_required
181
+def sale_edit(request, pk):
182
+    stores = request.user.store_created.all().order_by("-created_at")
183
+
184
+    obj = Sale.objects.get(pk=pk)
185
+    form = SaleForm(instance = obj)
186
+
187
+    if request.method == "POST":
188
+        form = SaleForm(request.POST)
189
+        if form.is_valid():
190
+            instance1 = form.save()
191
+            '''
192
+            print(instances)
193
+            for s in instances:
194
+                s.product = instance1
195
+                s.save()
196
+            '''
197
+            messages.success(request, "Sale Save")
198
+        else:
199
+            print("Invalid ")
200
+            if form.errors:
201
+                messages.error(request, form.errors)
202
+
203
+        return redirect("fruit:sale_edit", pk =  int(pk))
204
+
205
+    return render(request, 'fruit/sale_form.html', {'sale_active': True, 'form': form, 'object': obj})
206
+
207
+
208
+@login_required
209
+def inbox_index(request):
210
+    stores = request.user.store_created.all().order_by("-created_at")
211
+    o_qs = stores[0].inbox_set.all().order_by("-created_at")
212
+
213
+    f = InboxFilter(request.GET, queryset=o_qs)
214
+
215
+    paginator = Paginator(f.qs, 25)
216
+    page_number = request.GET.get('page')
217
+    page_obj = paginator.get_page(page_number)
218
+
219
+    return render(request, 'fruit/inbox_index.html', {'o_qs': o_qs, 'inbox_active': True, 'page_obj': page_obj, 'filter': f})
220
+
221
+@login_required
222
+def inbox_edit(request, pk):
223
+    stores = request.user.store_created.all().order_by("-created_at")
224
+
225
+    obj = Inbox.objects.get(pk=pk)
226
+    form = InboxForm(instance = obj)
227
+
228
+    if request.method == "POST":
229
+        form = InboxForm(request.POST)
230
+        if form.is_valid():
231
+            instance1 = form.save()
232
+            '''
233
+            print(instances)
234
+            for s in instances:
235
+                s.product = instance1
236
+                s.save()
237
+            '''
238
+            messages.success(request, "Sale Save")
239
+        else:
240
+            print("Invalid ")
241
+            if form.errors:
242
+                messages.error(request, form.errors)
243
+
244
+        return redirect("fruit:sale_edit", pk =  int(pk))
245
+
246
+    return render(request, 'fruit/inbox_form.html', {'inbox_active': True, 'form': form, 'object': obj})
155 247
 
156 248
 def signup(request):
157 249
     if request.method == 'POST':

+ 3 - 0
app/requirements.txt

@@ -14,3 +14,6 @@ Pillow
14 14
 django-quill-editor
15 15
 django-taggit
16 16
 django-crispy-forms
17
+django-filter
18
+django-paypal
19
+django-bootstrap-breadcrumbs

BIN
app/shaqfindbed/__pycache__/settings.cpython-39.pyc


+ 3 - 0
app/shaqfindbed/settings.py

@@ -47,12 +47,14 @@ INSTALLED_APPS = [
47 47
     'dal_select2',
48 48
     'mptt',
49 49
     'django_google_maps',
50
+    'django_bootstrap_breadcrumbs',
50 51
     'django.contrib.admin',
51 52
     'django.contrib.auth',
52 53
     'django.contrib.contenttypes',
53 54
     'django.contrib.sessions',
54 55
     'django.contrib.messages',
55 56
     'import_export',
57
+    'django_filters',
56 58
     'django_quill',
57 59
     'crispy_forms',
58 60
     'taggit',
@@ -171,3 +173,4 @@ LOGIN_REDIRECT_URL = '/fruit/mystore'
171 173
 LOGIN_URL = '/login'
172 174
 
173 175
 CRISPY_TEMPLATE_PACK = "bootstrap4"
176
+BREADCRUMBS_TEMPLATE = "django_bootstrap_breadcrumbs/bootstrap4.html"

tum/whitesports - Gogs: Simplico Git Service

暫無描述

class-requests.php 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. <?php
  2. /**
  3. * Requests for PHP
  4. *
  5. * Inspired by Requests for Python.
  6. *
  7. * Based on concepts from SimplePie_File, RequestCore and WP_Http.
  8. *
  9. * @package Requests
  10. */
  11. /**
  12. * Requests for PHP
  13. *
  14. * Inspired by Requests for Python.
  15. *
  16. * Based on concepts from SimplePie_File, RequestCore and WP_Http.
  17. *
  18. * @package Requests
  19. */
  20. class Requests {
  21. /**
  22. * POST method
  23. *
  24. * @var string
  25. */
  26. const POST = 'POST';
  27. /**
  28. * PUT method
  29. *
  30. * @var string
  31. */
  32. const PUT = 'PUT';
  33. /**
  34. * GET method
  35. *
  36. * @var string
  37. */
  38. const GET = 'GET';
  39. /**
  40. * HEAD method
  41. *
  42. * @var string
  43. */
  44. const HEAD = 'HEAD';
  45. /**
  46. * DELETE method
  47. *
  48. * @var string
  49. */
  50. const DELETE = 'DELETE';
  51. /**
  52. * OPTIONS method
  53. *
  54. * @var string
  55. */
  56. const OPTIONS = 'OPTIONS';
  57. /**
  58. * TRACE method
  59. *
  60. * @var string
  61. */
  62. const TRACE = 'TRACE';
  63. /**
  64. * PATCH method
  65. *
  66. * @link https://tools.ietf.org/html/rfc5789
  67. * @var string
  68. */
  69. const PATCH = 'PATCH';
  70. /**
  71. * Default size of buffer size to read streams
  72. *
  73. * @var integer
  74. */
  75. const BUFFER_SIZE = 1160;
  76. /**
  77. * Current version of Requests
  78. *
  79. * @var string
  80. */
  81. const VERSION = '1.8.1';
  82. /**
  83. * Registered transport classes
  84. *
  85. * @var array
  86. */
  87. protected static $transports = array();
  88. /**
  89. * Selected transport name
  90. *
  91. * Use {@see get_transport()} instead
  92. *
  93. * @var array
  94. */
  95. public static $transport = array();
  96. /**
  97. * Default certificate path.
  98. *
  99. * @see Requests::get_certificate_path()
  100. * @see Requests::set_certificate_path()
  101. *
  102. * @var string
  103. */
  104. protected static $certificate_path;
  105. /**
  106. * This is a static class, do not instantiate it
  107. *
  108. * @codeCoverageIgnore
  109. */
  110. private function __construct() {}
  111. /**
  112. * Autoloader for Requests
  113. *
  114. * Register this with {@see register_autoloader()} if you'd like to avoid
  115. * having to create your own.
  116. *
  117. * (You can also use `spl_autoload_register` directly if you'd prefer.)
  118. *
  119. * @codeCoverageIgnore
  120. *
  121. * @param string $class Class name to load
  122. */
  123. public static function autoloader($class) {
  124. // Check that the class starts with "Requests"
  125. if (strpos($class, 'Requests') !== 0) {
  126. return;
  127. }
  128. $file = str_replace('_', '/', $class);
  129. if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) {
  130. require_once dirname(__FILE__) . '/' . $file . '.php';
  131. }
  132. }
  133. /**
  134. * Register the built-in autoloader
  135. *
  136. * @codeCoverageIgnore
  137. */
  138. public static function register_autoloader() {
  139. spl_autoload_register(array('Requests', 'autoloader'));
  140. }
  141. /**
  142. * Register a transport
  143. *
  144. * @param string $transport Transport class to add, must support the Requests_Transport interface
  145. */
  146. public static function add_transport($transport) {
  147. if (empty(self::$transports)) {
  148. self::$transports = array(
  149. 'Requests_Transport_cURL',
  150. 'Requests_Transport_fsockopen',
  151. );
  152. }
  153. self::$transports = array_merge(self::$transports, array($transport));
  154. }
  155. /**
  156. * Get a working transport
  157. *
  158. * @throws Requests_Exception If no valid transport is found (`notransport`)
  159. * @return Requests_Transport
  160. */
  161. protected static function get_transport($capabilities = array()) {
  162. // Caching code, don't bother testing coverage
  163. // @codeCoverageIgnoreStart
  164. // array of capabilities as a string to be used as an array key
  165. ksort($capabilities);
  166. $cap_string = serialize($capabilities);
  167. // Don't search for a transport if it's already been done for these $capabilities
  168. if (isset(self::$transport[$cap_string]) && self::$transport[$cap_string] !== null) {
  169. $class = self::$transport[$cap_string];
  170. return new $class();
  171. }
  172. // @codeCoverageIgnoreEnd
  173. if (empty(self::$transports)) {
  174. self::$transports = array(
  175. 'Requests_Transport_cURL',
  176. 'Requests_Transport_fsockopen',
  177. );
  178. }
  179. // Find us a working transport
  180. foreach (self::$transports as $class) {
  181. if (!class_exists($class)) {
  182. continue;
  183. }
  184. $result = call_user_func(array($class, 'test'), $capabilities);
  185. if ($result) {
  186. self::$transport[$cap_string] = $class;
  187. break;
  188. }
  189. }
  190. if (self::$transport[$cap_string] === null) {
  191. throw new Requests_Exception('No working transports found', 'notransport', self::$transports);
  192. }
  193. $class = self::$transport[$cap_string];
  194. return new $class();
  195. }
  196. /**#@+
  197. * @see request()
  198. * @param string $url
  199. * @param array $headers
  200. * @param array $options
  201. * @return Requests_Response
  202. */
  203. /**
  204. * Send a GET request
  205. */
  206. public static function get($url, $headers = array(), $options = array()) {
  207. return self::request($url, $headers, null, self::GET, $options);
  208. }
  209. /**
  210. * Send a HEAD request
  211. */
  212. public static function head($url, $headers = array(), $options = array()) {
  213. return self::request($url, $headers, null, self::HEAD, $options);
  214. }
  215. /**
  216. * Send a DELETE request
  217. */
  218. public static function delete($url, $headers = array(), $options = array()) {
  219. return self::request($url, $headers, null, self::DELETE, $options);
  220. }
  221. /**
  222. * Send a TRACE request
  223. */
  224. public static function trace($url, $headers = array(), $options = array()) {
  225. return self::request($url, $headers, null, self::TRACE, $options);
  226. }
  227. /**#@-*/
  228. /**#@+
  229. * @see request()
  230. * @param string $url
  231. * @param array $headers
  232. * @param array $data
  233. * @param array $options
  234. * @return Requests_Response
  235. */
  236. /**
  237. * Send a POST request
  238. */
  239. public static function post($url, $headers = array(), $data = array(), $options = array()) {
  240. return self::request($url, $headers, $data, self::POST, $options);
  241. }
  242. /**
  243. * Send a PUT request
  244. */
  245. public static function put($url, $headers = array(), $data = array(), $options = array()) {
  246. return self::request($url, $headers, $data, self::PUT, $options);
  247. }
  248. /**
  249. * Send an OPTIONS request
  250. */
  251. public static function options($url, $headers = array(), $data = array(), $options = array()) {
  252. return self::request($url, $headers, $data, self::OPTIONS, $options);
  253. }
  254. /**
  255. * Send a PATCH request
  256. *
  257. * Note: Unlike {@see post} and {@see put}, `$headers` is required, as the
  258. * specification recommends that should send an ETag
  259. *
  260. * @link https://tools.ietf.org/html/rfc5789
  261. */
  262. public static function patch($url, $headers, $data = array(), $options = array()) {
  263. return self::request($url, $headers, $data, self::PATCH, $options);
  264. }
  265. /**#@-*/
  266. /**
  267. * Main interface for HTTP requests
  268. *
  269. * This method initiates a request and sends it via a transport before
  270. * parsing.
  271. *
  272. * The `$options` parameter takes an associative array with the following
  273. * options:
  274. *
  275. * - `timeout`: How long should we wait for a response?
  276. * Note: for cURL, a minimum of 1 second applies, as DNS resolution
  277. * operates at second-resolution only.
  278. * (float, seconds with a millisecond precision, default: 10, example: 0.01)
  279. * - `connect_timeout`: How long should we wait while trying to connect?
  280. * (float, seconds with a millisecond precision, default: 10, example: 0.01)
  281. * - `useragent`: Useragent to send to the server
  282. * (string, default: php-requests/$version)
  283. * - `follow_redirects`: Should we follow 3xx redirects?
  284. * (boolean, default: true)
  285. * - `redirects`: How many times should we redirect before erroring?
  286. * (integer, default: 10)
  287. * - `blocking`: Should we block processing on this request?
  288. * (boolean, default: true)
  289. * - `filename`: File to stream the body to instead.
  290. * (string|boolean, default: false)
  291. * - `auth`: Authentication handler or array of user/password details to use
  292. * for Basic authentication
  293. * (Requests_Auth|array|boolean, default: false)
  294. * - `proxy`: Proxy details to use for proxy by-passing and authentication
  295. * (Requests_Proxy|array|string|boolean, default: false)
  296. * - `max_bytes`: Limit for the response body size.
  297. * (integer|boolean, default: false)
  298. * - `idn`: Enable IDN parsing
  299. * (boolean, default: true)
  300. * - `transport`: Custom transport. Either a class name, or a
  301. * transport object. Defaults to the first working transport from
  302. * {@see getTransport()}
  303. * (string|Requests_Transport, default: {@see getTransport()})
  304. * - `hooks`: Hooks handler.
  305. * (Requests_Hooker, default: new Requests_Hooks())
  306. * - `verify`: Should we verify SSL certificates? Allows passing in a custom
  307. * certificate file as a string. (Using true uses the system-wide root
  308. * certificate store instead, but this may have different behaviour
  309. * across transports.)
  310. * (string|boolean, default: library/Requests/Transport/cacert.pem)
  311. * - `verifyname`: Should we verify the common name in the SSL certificate?
  312. * (boolean, default: true)
  313. * - `data_format`: How should we send the `$data` parameter?
  314. * (string, one of 'query' or 'body', default: 'query' for
  315. * HEAD/GET/DELETE, 'body' for POST/PUT/OPTIONS/PATCH)
  316. *
  317. * @throws Requests_Exception On invalid URLs (`nonhttp`)
  318. *
  319. * @param string $url URL to request
  320. * @param array $headers Extra headers to send with the request
  321. * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
  322. * @param string $type HTTP request type (use Requests constants)
  323. * @param array $options Options for the request (see description for more information)
  324. * @return Requests_Response
  325. */
  326. public static function request($url, $headers = array(), $data = array(), $type = self::GET, $options = array()) {
  327. if (empty($options['type'])) {
  328. $options['type'] = $type;
  329. }
  330. $options = array_merge(self::get_default_options(), $options);
  331. self::set_defaults($url, $headers, $data, $type, $options);
  332. $options['hooks']->dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options));
  333. if (!empty($options['transport'])) {
  334. $transport = $options['transport'];
  335. if (is_string($options['transport'])) {
  336. $transport = new $transport();
  337. }
  338. }
  339. else {
  340. $need_ssl = (stripos($url, 'https://') === 0);
  341. $capabilities = array('ssl' => $need_ssl);
  342. $transport = self::get_transport($capabilities);
  343. }
  344. $response = $transport->request($url, $headers, $data, $options);
  345. $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options));
  346. return self::parse_response($response, $url, $headers, $data, $options);
  347. }
  348. /**
  349. * Send multiple HTTP requests simultaneously
  350. *
  351. * The `$requests` parameter takes an associative or indexed array of
  352. * request fields. The key of each request can be used to match up the
  353. * request with the returned data, or with the request passed into your
  354. * `multiple.request.complete` callback.
  355. *
  356. * The request fields value is an associative array with the following keys:
  357. *
  358. * - `url`: Request URL Same as the `$url` parameter to
  359. * {@see Requests::request}
  360. * (string, required)
  361. * - `headers`: Associative array of header fields. Same as the `$headers`
  362. * parameter to {@see Requests::request}
  363. * (array, default: `array()`)
  364. * - `data`: Associative array of data fields or a string. Same as the
  365. * `$data` parameter to {@see Requests::request}
  366. * (array|string, default: `array()`)
  367. * - `type`: HTTP request type (use Requests constants). Same as the `$type`
  368. * parameter to {@see Requests::request}
  369. * (string, default: `Requests::GET`)
  370. * - `cookies`: Associative array of cookie name to value, or cookie jar.
  371. * (array|Requests_Cookie_Jar)
  372. *
  373. * If the `$options` parameter is specified, individual requests will
  374. * inherit options from it. This can be used to use a single hooking system,
  375. * or set all the types to `Requests::POST`, for example.
  376. *
  377. * In addition, the `$options` parameter takes the following global options:
  378. *
  379. * - `complete`: A callback for when a request is complete. Takes two
  380. * parameters, a Requests_Response/Requests_Exception reference, and the
  381. * ID from the request array (Note: this can also be overridden on a
  382. * per-request basis, although that's a little silly)
  383. * (callback)
  384. *
  385. * @param array $requests Requests data (see description for more information)
  386. * @param array $options Global and default options (see {@see Requests::request})
  387. * @return array Responses (either Requests_Response or a Requests_Exception object)
  388. */
  389. public static function request_multiple($requests, $options = array()) {
  390. $options = array_merge(self::get_default_options(true), $options);
  391. if (!empty($options['hooks'])) {
  392. $options['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
  393. if (!empty($options['complete'])) {
  394. $options['hooks']->register('multiple.request.complete', $options['complete']);
  395. }
  396. }
  397. foreach ($requests as $id => &$request) {
  398. if (!isset($request['headers'])) {
  399. $request['headers'] = array();
  400. }
  401. if (!isset($request['data'])) {
  402. $request['data'] = array();
  403. }
  404. if (!isset($request['type'])) {
  405. $request['type'] = self::GET;
  406. }
  407. if (!isset($request['options'])) {
  408. $request['options'] = $options;
  409. $request['options']['type'] = $request['type'];
  410. }
  411. else {
  412. if (empty($request['options']['type'])) {
  413. $request['options']['type'] = $request['type'];
  414. }
  415. $request['options'] = array_merge($options, $request['options']);
  416. }
  417. self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']);
  418. // Ensure we only hook in once
  419. if ($request['options']['hooks'] !== $options['hooks']) {
  420. $request['options']['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
  421. if (!empty($request['options']['complete'])) {
  422. $request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']);
  423. }
  424. }
  425. }
  426. unset($request);
  427. if (!empty($options['transport'])) {
  428. $transport = $options['transport'];
  429. if (is_string($options['transport'])) {
  430. $transport = new $transport();
  431. }
  432. }
  433. else {
  434. $transport = self::get_transport();
  435. }
  436. $responses = $transport->request_multiple($requests, $options);
  437. foreach ($responses as $id => &$response) {
  438. // If our hook got messed with somehow, ensure we end up with the
  439. // correct response
  440. if (is_string($response)) {
  441. $request = $requests[$id];
  442. self::parse_multiple($response, $request);
  443. $request['options']['hooks']->dispatch('multiple.request.complete', array(&$response, $id));
  444. }
  445. }
  446. return $responses;
  447. }
  448. /**
  449. * Get the default options
  450. *
  451. * @see Requests::request() for values returned by this method
  452. * @param boolean $multirequest Is this a multirequest?
  453. * @return array Default option values
  454. */
  455. protected static function get_default_options($multirequest = false) {
  456. $defaults = array(
  457. 'timeout' => 10,
  458. 'connect_timeout' => 10,
  459. 'useragent' => 'php-requests/' . self::VERSION,
  460. 'protocol_version' => 1.1,
  461. 'redirected' => 0,
  462. 'redirects' => 10,
  463. 'follow_redirects' => true,
  464. 'blocking' => true,
  465. 'type' => self::GET,
  466. 'filename' => false,
  467. 'auth' => false,
  468. 'proxy' => false,
  469. 'cookies' => false,
  470. 'max_bytes' => false,
  471. 'idn' => true,
  472. 'hooks' => null,
  473. 'transport' => null,
  474. 'verify' => self::get_certificate_path(),
  475. 'verifyname' => true,
  476. );
  477. if ($multirequest !== false) {
  478. $defaults['complete'] = null;
  479. }
  480. return $defaults;
  481. }
  482. /**
  483. * Get default certificate path.
  484. *
  485. * @return string Default certificate path.
  486. */
  487. public static function get_certificate_path() {
  488. if (!empty(self::$certificate_path)) {
  489. return self::$certificate_path;
  490. }
  491. return dirname(__FILE__) . '/Requests/Transport/cacert.pem';
  492. }
  493. /**
  494. * Set default certificate path.
  495. *
  496. * @param string $path Certificate path, pointing to a PEM file.
  497. */
  498. public static function set_certificate_path($path) {
  499. self::$certificate_path = $path;
  500. }
  501. /**
  502. * Set the default values
  503. *
  504. * @param string $url URL to request
  505. * @param array $headers Extra headers to send with the request
  506. * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
  507. * @param string $type HTTP request type
  508. * @param array $options Options for the request
  509. * @return array $options
  510. */
  511. protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
  512. if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
  513. throw new Requests_Exception('Only HTTP(S) requests are handled.', 'nonhttp', $url);
  514. }
  515. if (empty($options['hooks'])) {
  516. $options['hooks'] = new Requests_Hooks();
  517. }
  518. if (is_array($options['auth'])) {
  519. $options['auth'] = new Requests_Auth_Basic($options['auth']);
  520. }
  521. if ($options['auth'] !== false) {
  522. $options['auth']->register($options['hooks']);
  523. }
  524. if (is_string($options['proxy']) || is_array($options['proxy'])) {
  525. $options['proxy'] = new Requests_Proxy_HTTP($options['proxy']);
  526. }
  527. if ($options['proxy'] !== false) {
  528. $options['proxy']->register($options['hooks']);
  529. }
  530. if (is_array($options['cookies'])) {
  531. $options['cookies'] = new Requests_Cookie_Jar($options['cookies']);
  532. }
  533. elseif (empty($options['cookies'])) {
  534. $options['cookies'] = new Requests_Cookie_Jar();
  535. }
  536. if ($options['cookies'] !== false) {
  537. $options['cookies']->register($options['hooks']);
  538. }
  539. if ($options['idn'] !== false) {
  540. $iri = new Requests_IRI($url);
  541. $iri->host = Requests_IDNAEncoder::encode($iri->ihost);
  542. $url = $iri->uri;
  543. }
  544. // Massage the type to ensure we support it.
  545. $type = strtoupper($type);
  546. if (!isset($options['data_format'])) {
  547. if (in_array($type, array(self::HEAD, self::GET, self::DELETE), true)) {
  548. $options['data_format'] = 'query';
  549. }
  550. else {
  551. $options['data_format'] = 'body';
  552. }
  553. }
  554. }
  555. /**
  556. * HTTP response parser
  557. *
  558. * @throws Requests_Exception On missing head/body separator (`requests.no_crlf_separator`)
  559. * @throws Requests_Exception On missing head/body separator (`noversion`)
  560. * @throws Requests_Exception On missing head/body separator (`toomanyredirects`)
  561. *
  562. * @param string $headers Full response text including headers and body
  563. * @param string $url Original request URL
  564. * @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects
  565. * @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects
  566. * @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects
  567. * @return Requests_Response
  568. */
  569. protected static function parse_response($headers, $url, $req_headers, $req_data, $options) {
  570. $return = new Requests_Response();
  571. if (!$options['blocking']) {
  572. return $return;
  573. }
  574. $return->raw = $headers;
  575. $return->url = (string) $url;
  576. $return->body = '';
  577. if (!$options['filename']) {
  578. $pos = strpos($headers, "\r\n\r\n");
  579. if ($pos === false) {
  580. // Crap!
  581. throw new Requests_Exception('Missing header/body separator', 'requests.no_crlf_separator');
  582. }
  583. $headers = substr($return->raw, 0, $pos);
  584. // Headers will always be separated from the body by two new lines - `\n\r\n\r`.
  585. $body = substr($return->raw, $pos + 4);
  586. if (!empty($body)) {
  587. $return->body = $body;
  588. }
  589. }
  590. // Pretend CRLF = LF for compatibility (RFC 2616, section 19.3)
  591. $headers = str_replace("\r\n", "\n", $headers);
  592. // Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2)
  593. $headers = preg_replace('/\n[ \t]/', ' ', $headers);
  594. $headers = explode("\n", $headers);
  595. preg_match('#^HTTP/(1\.\d)[ \t]+(\d+)#i', array_shift($headers), $matches);
  596. if (empty($matches)) {
  597. throw new Requests_Exception('Response could not be parsed', 'noversion', $headers);
  598. }
  599. $return->protocol_version = (float) $matches[1];
  600. $return->status_code = (int) $matches[2];
  601. if ($return->status_code >= 200 && $return->status_code < 300) {
  602. $return->success = true;
  603. }
  604. foreach ($headers as $header) {
  605. list($key, $value) = explode(':', $header, 2);
  606. $value = trim($value);
  607. preg_replace('#(\s+)#i', ' ', $value);
  608. $return->headers[$key] = $value;
  609. }
  610. if (isset($return->headers['transfer-encoding'])) {
  611. $return->body = self::decode_chunked($return->body);
  612. unset($return->headers['transfer-encoding']);
  613. }
  614. if (isset($return->headers['content-encoding'])) {
  615. $return->body = self::decompress($return->body);
  616. }
  617. //fsockopen and cURL compatibility
  618. if (isset($return->headers['connection'])) {
  619. unset($return->headers['connection']);
  620. }
  621. $options['hooks']->dispatch('requests.before_redirect_check', array(&$return, $req_headers, $req_data, $options));
  622. if ($return->is_redirect() && $options['follow_redirects'] === true) {
  623. if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) {
  624. if ($return->status_code === 303) {
  625. $options['type'] = self::GET;
  626. }
  627. $options['redirected']++;
  628. $location = $return->headers['location'];
  629. if (strpos($location, 'http://') !== 0 && strpos($location, 'https://') !== 0) {
  630. // relative redirect, for compatibility make it absolute
  631. $location = Requests_IRI::absolutize($url, $location);
  632. $location = $location->uri;
  633. }
  634. $hook_args = array(
  635. &$location,
  636. &$req_headers,
  637. &$req_data,
  638. &$options,
  639. $return,
  640. );
  641. $options['hooks']->dispatch('requests.before_redirect', $hook_args);
  642. $redirected = self::request($location, $req_headers, $req_data, $options['type'], $options);
  643. $redirected->history[] = $return;
  644. return $redirected;
  645. }
  646. elseif ($options['redirected'] >= $options['redirects']) {
  647. throw new Requests_Exception('Too many redirects', 'toomanyredirects', $return);
  648. }
  649. }
  650. $return->redirects = $options['redirected'];
  651. $options['hooks']->dispatch('requests.after_request', array(&$return, $req_headers, $req_data, $options));
  652. return $return;
  653. }
  654. /**
  655. * Callback for `transport.internal.parse_response`
  656. *
  657. * Internal use only. Converts a raw HTTP response to a Requests_Response
  658. * while still executing a multiple request.
  659. *
  660. * @param string $response Full response text including headers and body (will be overwritten with Response instance)
  661. * @param array $request Request data as passed into {@see Requests::request_multiple()}
  662. * @return null `$response` is either set to a Requests_Response instance, or a Requests_Exception object
  663. */
  664. public static function parse_multiple(&$response, $request) {
  665. try {
  666. $url = $request['url'];
  667. $headers = $request['headers'];
  668. $data = $request['data'];
  669. $options = $request['options'];
  670. $response = self::parse_response($response, $url, $headers, $data, $options);
  671. }
  672. catch (Requests_Exception $e) {
  673. $response = $e;
  674. }
  675. }
  676. /**
  677. * Decoded a chunked body as per RFC 2616
  678. *
  679. * @see https://tools.ietf.org/html/rfc2616#section-3.6.1
  680. * @param string $data Chunked body
  681. * @return string Decoded body
  682. */
  683. protected static function decode_chunked($data) {
  684. if (!preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', trim($data))) {
  685. return $data;
  686. }
  687. $decoded = '';
  688. $encoded = $data;
  689. while (true) {
  690. $is_chunked = (bool) preg_match('/^([0-9a-f]+)(?:;(?:[\w-]*)(?:=(?:(?:[\w-]*)*|"(?:[^\r\n])*"))?)*\r\n/i', $encoded, $matches);
  691. if (!$is_chunked) {
  692. // Looks like it's not chunked after all
  693. return $data;
  694. }
  695. $length = hexdec(trim($matches[1]));
  696. if ($length === 0) {
  697. // Ignore trailer headers
  698. return $decoded;
  699. }
  700. $chunk_length = strlen($matches[0]);
  701. $decoded .= substr($encoded, $chunk_length, $length);
  702. $encoded = substr($encoded, $chunk_length + $length + 2);
  703. if (trim($encoded) === '0' || empty($encoded)) {
  704. return $decoded;
  705. }
  706. }
  707. // We'll never actually get down here
  708. // @codeCoverageIgnoreStart
  709. }
  710. // @codeCoverageIgnoreEnd
  711. /**
  712. * Convert a key => value array to a 'key: value' array for headers
  713. *
  714. * @param array $array Dictionary of header values
  715. * @return array List of headers
  716. */
  717. public static function flatten($array) {
  718. $return = array();
  719. foreach ($array as $key => $value) {
  720. $return[] = sprintf('%s: %s', $key, $value);
  721. }
  722. return $return;
  723. }
  724. /**
  725. * Convert a key => value array to a 'key: value' array for headers
  726. *
  727. * @codeCoverageIgnore
  728. * @deprecated Misspelling of {@see Requests::flatten}
  729. * @param array $array Dictionary of header values
  730. * @return array List of headers
  731. */
  732. public static function flattern($array) {
  733. return self::flatten($array);
  734. }
  735. /**
  736. * Decompress an encoded body
  737. *
  738. * Implements gzip, compress and deflate. Guesses which it is by attempting
  739. * to decode.
  740. *
  741. * @param string $data Compressed data in one of the above formats
  742. * @return string Decompressed string
  743. */
  744. public static function decompress($data) {
  745. if (substr($data, 0, 2) !== "\x1f\x8b" && substr($data, 0, 2) !== "\x78\x9c") {
  746. // Not actually compressed. Probably cURL ruining this for us.
  747. return $data;
  748. }
  749. if (function_exists('gzdecode')) {
  750. // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.gzdecodeFound -- Wrapped in function_exists() for PHP 5.2.
  751. $decoded = @gzdecode($data);
  752. if ($decoded !== false) {
  753. return $decoded;
  754. }
  755. }
  756. if (function_exists('gzinflate')) {
  757. $decoded = @gzinflate($data);
  758. if ($decoded !== false) {
  759. return $decoded;
  760. }
  761. }
  762. $decoded = self::compatible_gzinflate($data);
  763. if ($decoded !== false) {
  764. return $decoded;
  765. }
  766. if (function_exists('gzuncompress')) {
  767. $decoded = @gzuncompress($data);
  768. if ($decoded !== false) {
  769. return $decoded;
  770. }
  771. }
  772. return $data;
  773. }
  774. /**
  775. * Decompression of deflated string while staying compatible with the majority of servers.
  776. *
  777. * Certain Servers will return deflated data with headers which PHP's gzinflate()
  778. * function cannot handle out of the box. The following function has been created from
  779. * various snippets on the gzinflate() PHP documentation.
  780. *
  781. * Warning: Magic numbers within. Due to the potential different formats that the compressed
  782. * data may be returned in, some "magic offsets" are needed to ensure proper decompression
  783. * takes place. For a simple progmatic way to determine the magic offset in use, see:
  784. * https://core.trac.wordpress.org/ticket/18273
  785. *
  786. * @since 2.8.1
  787. * @link https://core.trac.wordpress.org/ticket/18273
  788. * @link https://secure.php.net/manual/en/function.gzinflate.php#70875
  789. * @link https://secure.php.net/manual/en/function.gzinflate.php#77336
  790. *
  791. * @param string $gz_data String to decompress.
  792. * @return string|bool False on failure.
  793. */
  794. public static function compatible_gzinflate($gz_data) {
  795. // Compressed data might contain a full zlib header, if so strip it for
  796. // gzinflate()
  797. if (substr($gz_data, 0, 3) === "\x1f\x8b\x08") {
  798. $i = 10;
  799. $flg = ord(substr($gz_data, 3, 1));
  800. if ($flg > 0) {
  801. if ($flg & 4) {
  802. list($xlen) = unpack('v', substr($gz_data, $i, 2));
  803. $i += 2 + $xlen;
  804. }
  805. if ($flg & 8) {
  806. $i = strpos($gz_data, "\0", $i) + 1;
  807. }
  808. if ($flg & 16) {
  809. $i = strpos($gz_data, "\0", $i) + 1;
  810. }
  811. if ($flg & 2) {
  812. $i += 2;
  813. }
  814. }
  815. $decompressed = self::compatible_gzinflate(substr($gz_data, $i));
  816. if ($decompressed !== false) {
  817. return $decompressed;
  818. }
  819. }
  820. // If the data is Huffman Encoded, we must first strip the leading 2
  821. // byte Huffman marker for gzinflate()
  822. // The response is Huffman coded by many compressors such as
  823. // java.util.zip.Deflater, Ruby’s Zlib::Deflate, and .NET's
  824. // System.IO.Compression.DeflateStream.
  825. //
  826. // See https://decompres.blogspot.com/ for a quick explanation of this
  827. // data type
  828. $huffman_encoded = false;
  829. // low nibble of first byte should be 0x08
  830. list(, $first_nibble) = unpack('h', $gz_data);
  831. // First 2 bytes should be divisible by 0x1F
  832. list(, $first_two_bytes) = unpack('n', $gz_data);
  833. if ($first_nibble === 0x08 && ($first_two_bytes % 0x1F) === 0) {
  834. $huffman_encoded = true;
  835. }
  836. if ($huffman_encoded) {
  837. $decompressed = @gzinflate(substr($gz_data, 2));
  838. if ($decompressed !== false) {
  839. return $decompressed;
  840. }
  841. }
  842. if (substr($gz_data, 0, 4) === "\x50\x4b\x03\x04") {
  843. // ZIP file format header
  844. // Offset 6: 2 bytes, General-purpose field
  845. // Offset 26: 2 bytes, filename length
  846. // Offset 28: 2 bytes, optional field length
  847. // Offset 30: Filename field, followed by optional field, followed
  848. // immediately by data
  849. list(, $general_purpose_flag) = unpack('v', substr($gz_data, 6, 2));
  850. // If the file has been compressed on the fly, 0x08 bit is set of
  851. // the general purpose field. We can use this to differentiate
  852. // between a compressed document, and a ZIP file
  853. $zip_compressed_on_the_fly = ((0x08 & $general_purpose_flag) === 0x08);
  854. if (!$zip_compressed_on_the_fly) {
  855. // Don't attempt to decode a compressed zip file
  856. return $gz_data;
  857. }
  858. // Determine the first byte of data, based on the above ZIP header
  859. // offsets:
  860. $first_file_start = array_sum(unpack('v2', substr($gz_data, 26, 4)));
  861. $decompressed = @gzinflate(substr($gz_data, 30 + $first_file_start));
  862. if ($decompressed !== false) {
  863. return $decompressed;
  864. }
  865. return false;
  866. }
  867. // Finally fall back to straight gzinflate
  868. $decompressed = @gzinflate($gz_data);
  869. if ($decompressed !== false) {
  870. return $decompressed;
  871. }
  872. // Fallback for all above failing, not expected, but included for
  873. // debugging and preventing regressions and to track stats
  874. $decompressed = @gzinflate(substr($gz_data, 2));
  875. if ($decompressed !== false) {
  876. return $decompressed;
  877. }
  878. return false;
  879. }
  880. public static function match_domain($host, $reference) {
  881. // Check for a direct match
  882. if ($host === $reference) {
  883. return true;
  884. }
  885. // Calculate the valid wildcard match if the host is not an IP address
  886. // Also validates that the host has 3 parts or more, as per Firefox's
  887. // ruleset.
  888. $parts = explode('.', $host);
  889. if (ip2long($host) === false && count($parts) >= 3) {
  890. $parts[0] = '*';
  891. $wildcard = implode('.', $parts);
  892. if ($wildcard === $reference) {
  893. return true;
  894. }
  895. }
  896. return false;
  897. }
  898. }